package com.gsmr.controller;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gsmr.entity.*;
import com.gsmr.service.SDCCHService;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.gsmr.service.BS_infoService;
import com.gsmr.service.InterferenceQueryService;
import com.gsmr.service.SysOperationRecordService;
import com.gsmr.util.Calintermodu;
import com.gsmr.util.DateUtil;
import com.gsmr.util.ExcelUtil;
import com.gsmr.util.FormatDate;
import com.gsmr.util.PropertityUtil;
import com.gsmr.util.ResponseUtil;
import com.gsmr.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

/**
 * InterferenceQuery控制层
 */
@Controller
@RequestMapping("/interferencequery")
public class InterferenceQueryController {
	
	@Resource
	private InterferenceQueryService interferencequeryService;

	@Resource
	private SysOperationRecordService sysOperationRecordService;
	@Resource
	private SDCCHService sdcchService;
	
	
	
	
	/**
	 * 分页条件查询干扰记录
	 */
	@RequestMapping("/list")
	public void list(@RequestParam(value="page",required=false)String page,@RequestParam(value="rows",required=false)String rows,
			@RequestParam(value="startTime",required=false)String startTime,@RequestParam(value="endTime",required=false)String endTime,
			@RequestParam(value="frontId",required=false)String frontId,@RequestParam(value="interference_type",required=false)String interference_type,
			@RequestParam(value="disposed",required=false)String disposed,@RequestParam(value="isHistory",required=false)String isHistory,
			@RequestParam(value="releaseWay",required=false)String releaseWay,HttpServletResponse response)throws Exception{
        if(isHistory == null) return;

		System.out.println("startTime:============="+startTime);
		System.out.println("endTime:============="+endTime);
		PageBean pageBean=new PageBean(Integer.parseInt(page.trim()),Integer.parseInt(rows.trim()));
		Map<String,Object> map = new HashMap<>();
		
		if (frontId != null && frontId.trim().length() > 0) {
			
			String[] subdistrict = frontId.split(",");
			String[] frontID = new String[subdistrict.length];
			
			for (int i = 0; i < subdistrict.length; i++) {
				if (subdistrict[i].trim().length() < 1) continue;
				map.put("frontId", subdistrict[i]);
				map.put("table_name","bs_info");
				frontID[i] = interferencequeryService.get_frontId(map);
			}
			List<String> subList = Arrays.asList(frontID);
			map.put("district", subList);
			System.out.println(map);
		}
		if (interference_type != null && interference_type.trim().length() > 0) {
			String[] infTypes = interference_type.split(",");
			
			map.put("interference_types", Arrays.asList(infTypes));
		}
		map.put("start", pageBean.getStart());
		if (startTime!=null && !startTime.equals("NaN")) {
			map.put("startTime", startTime);
		}
		if (endTime!=null && !endTime.equals("NaN")) {
			map.put("endTime", endTime);
		}
		map.put("size", pageBean.getPageSize());
		
		if (disposed!=null && !disposed.equals("")) {
			if (disposed.equals("是")) {
				map.put("disposed", "1");
			} else if (disposed.equals("否")) {
				map.put("disposed", "0");
			}
		}
		if (releaseWay!=null && !releaseWay.equals("NaN")) {
			if (releaseWay.equals("自动消除")) {
				map.put("releaseWay", releaseWay);
			} else if (releaseWay.equals("手动确认")) {
				map.put("releaseWay", releaseWay);
			}
		}
		List<Interference> interferenceList = new ArrayList<>();
		
		if(isHistory.equals("1")) {
			map.put("table_name","interference_history");
		}
		else {
			map.put("table_name","interference_real_time");
		}
		
		
		List<Interference> sub_sdcchList = interferencequeryService.find(map);
		interferenceList.addAll(sub_sdcchList);
		Long total=interferencequeryService.getTotal(map);
		JSONObject result=new JSONObject();
		JSONArray jsonArray=JSONArray.fromObject(interferenceList);
		for (int i = 0; i < jsonArray.size(); i++) {  
            JSONObject json=new JSONObject();  
            json=jsonArray.getJSONObject(i);  
            String Direction="下行";
            String dis="否";
            String kil="";
            String fchannel="";
            String schannel="";
			Object timestart = json.get("timeBegin");
			Object timeend = json.get("timeEnd");
			Object dir = json.get("direction");
			Object isdisposed=json.get("disposed");
			Object kilometer=json.get("kilometer");
			Object releasetime=json.get("releaseTime");
			Object firstchannel=json.get("infMaxChannel");
			Object secondchannel=json.get("infSecChannel");
			String start = converttime((String) timestart);
			String end = converttime((String) timeend);
			String rtime = "";
            if (dir.equals("0"))
            	Direction="上行";
            if(isdisposed.equals("1"))
			{
            	dis="是";
				rtime = converttime((String) releasetime);
			}

            kil=kilometer.toString();
            if(kilometer.equals("0")) {
            	kil="";
            }
            fchannel=firstchannel.toString();
            if(firstchannel.equals("0"))
            	fchannel="";
            schannel=secondchannel.toString();
            if(secondchannel.equals("0"))
            	schannel="";
            jsonArray.getJSONObject(i).put("timeBegin", start);
            jsonArray.getJSONObject(i).put("timeEnd", end);
            jsonArray.getJSONObject(i).put("direction", Direction);
            jsonArray.getJSONObject(i).put("disposed", dis);
            jsonArray.getJSONObject(i).put("kilometer", kil);
            jsonArray.getJSONObject(i).put("releaseTime", rtime);
            jsonArray.getJSONObject(i).put("infMaxChannel", fchannel);
            jsonArray.getJSONObject(i).put("infSecChannel", schannel);
		}
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
	}



	/**
	 * 分页条件查询干扰度记录
	 */
	@RequestMapping("/interfaceoccupylist")
	public void interfaceoccupylist(@RequestParam(value="page",required=false)String page,@RequestParam(value="rows",required=false)String rows,
					 @RequestParam(value="startTime",required=false)String startTime,@RequestParam(value="endTime",required=false)String endTime,
					 @RequestParam(value="frontId",required=false)String frontId,HttpServletResponse response)throws Exception{
		System.out.println("startTime:============="+startTime);
		System.out.println("endTime:============="+endTime);
		double startdate=  Double.parseDouble(startTime);
		double enddate=  Double.parseDouble(endTime);
		double offest=(enddate-startdate)/1000;
		PageBean pageBean=new PageBean(Integer.parseInt(page.trim()),Integer.parseInt(rows.trim()));
		Map<String,Object> map = new HashMap<>();
//		System.out.println("前端传来的frontId：=="+frontId);
		if (frontId != null && frontId.trim().length() > 0) {

			String[] subdistrict = frontId.split(",");
			String[] frontID = new String[subdistrict.length];

			for (int i = 0; i < subdistrict.length; i++) {
				if (subdistrict[i].trim().length() < 1) continue;
//				System.out.println("frontId===="+subdistrict[i]);
				map.put("frontId", subdistrict[i]);
				map.put("table_name","bs_info");
				if(null!=interferencequeryService.get_frontId(map)) {
					frontID[i] = interferencequeryService.get_frontId(map);
//					System.out.println("frontID[i]============="+frontID[i]);
				}
			}
			List<String> subList = Arrays.asList(frontID);
			map.put("district", subList);
//			System.out.println("BSNname集合：======="+map.get("district").toString());
		}
		map.put("start", pageBean.getStart());
		if (startTime!=null && !startTime.equals("NaN")) {
			map.put("startTime", startTime);
		}
		if (endTime!=null && !endTime.equals("NaN")) {
			map.put("endTime", endTime);
		}
		map.put("size", pageBean.getPageSize());

		List<InterfaceOccupy> interferenceList = new ArrayList<>();

		List<InterfaceOccupy> sub_sdcchList = interferencequeryService.findByOccupy(map);
		for (InterfaceOccupy occupy:sub_sdcchList
			 ) {
			occupy.setOffest(String.valueOf(offest));
//			System.out.println("occupy.getDiff():==="+occupy.getDiff());
			if(occupy.getDiff()!=null) {
				occupy.setInfpercentage(String.valueOf((Double.parseDouble(occupy.getDiff()) / offest) * 100));
//				System.out.println("occupyInfpercentage:===" + occupy.getInfpercentage());
			}
		}
		interferenceList.addAll(sub_sdcchList);
		Long total=interferencequeryService.getOccupyTotal(map);
//		System.out.println("干扰度记录总数："+total);
		JSONObject result=new JSONObject();
		JSONArray jsonArray=JSONArray.fromObject(interferenceList);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject json=new JSONObject();
			json=jsonArray.getJSONObject(i);
			String Direction="下行";
			Object dir = json.get("direction");
			if (dir.equals("0"))
				Direction="上行";
			jsonArray.getJSONObject(i).put("direction", Direction);
		}
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
	}


	/**
	 * 导出所有干扰记录
	 *
	 * @param
	 * @param
	 * @param
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/exportoccupy")
	public String exportoccupy(@RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime,
							  @RequestParam(value = "frontId", required = false) String frontId, HttpServletResponse response) throws Exception {
		Workbook wb = new HSSFWorkbook();
		String headers[] = {"小区", "方向", "频点", "干扰信号峰值（dBm）", "干扰时长（秒）", "总时长（秒）", "干扰占用度（%）" };
		Map<String, Object> map = new HashMap<String, Object>();
		DecimalFormat df=new DecimalFormat("#0.00");
		double startdate=  Double.parseDouble(startTime);
		double enddate=  Double.parseDouble(endTime);
		double offest=(enddate-startdate)/1000;
		String offeststr=df.format((enddate-startdate)/1000);
//		if (frontId != null && !frontId.equals("")) {
//			map.put("frontId", frontId);
//			map.put("table_name", "bs_info");
//			String front_Id = interferencequeryService.get_frontId(map);
//			map.put("frontId", front_Id);
//		}
		if (frontId != null && frontId.trim().length() > 0) {

			String[] subdistrict = frontId.split(",");
			String[] frontID = new String[subdistrict.length];

			for (int i = 0; i < subdistrict.length; i++) {
				if (subdistrict[i].trim().length() < 1) continue;
				map.put("frontId", subdistrict[i]);
				map.put("table_name","bs_info");
				frontID[i] = interferencequeryService.get_frontId(map);
			}
			List<String> subList = Arrays.asList(frontID);
			map.put("district", subList);
			System.out.println(map);
		}
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", startTime);
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", endTime);
		}
		List<InterfaceOccupy> interferenceList = new ArrayList<InterfaceOccupy>();
		System.out.println(map);
		List<InterfaceOccupy> sub_sdcchList = interferencequeryService.findByOccupy(map);
		interferenceList.addAll(sub_sdcchList);
		List<InterfaceOccupy> interferenceList_all = new ArrayList<InterfaceOccupy>();
		for (InterfaceOccupy interference : interferenceList) {
			String dir;
			String Direction = "下行";
			dir = interference.getDirection();
			if (dir.equals("0"))
				Direction = "上行";
			interference.setDirection(Direction);
			interference.setOffest(offeststr);
			System.out.println("occupy.getDiff():==="+interference.getDiff());
			if(interference.getDiff()!=null) {
				interference.setInfpercentage(String.valueOf(df.format((Double.parseDouble(interference.getDiff()) / offest) * 100)));
//				System.out.println("occupyInfpercentage:===" + interference.getInfpercentage());
			}
			interferenceList_all.add(interference);
		}
		try {
			ExcelUtil.fillExcelData_InterferenceOccuryQuery(interferenceList_all, wb, headers);
			ResponseUtil.export(response, wb, "干扰占用度统计记录" + FormatDate.formatDate() + ".xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}





	@RequestMapping("/findCurrentDate")
	public void findCurrentDate(@RequestParam(value = "data") double data,
			@RequestParam(value="startTime",required=false)String startTime,
			@RequestParam(value="frontId",required=false)String frontId,HttpServletResponse response) throws Exception {
		String time1 = "";
		String front_Id="";
		Map<String,Object> map=new HashMap<String,Object>();
		if(startTime!=null&&!startTime.equals("NaN")){
			//tmp=timetoStamp(startTime);
			map.put("startTime", startTime);
			time1 = returndate(Long.parseLong(startTime));
		}
		if(frontId!=null&&!frontId.equals("")){
			map.put("frontId", frontId);
			map.put("table_name","bs_info");
			front_Id=interferencequeryService.get_frontId(map);
			map.put("frontId", front_Id);
		}

        map.put("table_name", "frequencySpectrum_"+ front_Id+"_"+time1);
		
		Integer count = interferencequeryService.findTotalCount(map);
		
		Integer offset = (int) (count * data / 100);
		System.out.println("count * data = " + count + " * " + data + " = " + offset);
		if (offset < 1) {
			return;
		}
		
		map.put("offset", offset);
		InfFrequencySpectrum inf = interferencequeryService.findOffset(map);

		JSONObject result=new JSONObject();
		result.put("rows", inf);
		ResponseUtil.write(response, result);
		
		System.out.println("count: " + count);
	}
	
	
	/**
	 * 导出当前页的数据
	 */
	@RequestMapping("/exportcurrentpage")
	public void exportcurrentData(@RequestParam(value = "data") String data, HttpServletResponse response) throws Exception {
		
		if (data == null || data.equals("null") || data.length() < 2) return;

		JSONArray jsonArray = JSONArray.fromObject(data);
		List<FScan> tchSignalingList = (List<FScan>) JSONArray.toCollection(jsonArray, FScan.class);

		//TCHController.ListSortSignaling(tchSignalingList);
		
		String headers[] = { "扫描时间 ","前置机号 ","基站","文件名编号 ","MCC","MNC","LAC","CID","BCCH","BSIC","RXLEV","TRXs"};
		Workbook wb = new HSSFWorkbook();
		ExcelUtil.fillExcelData_FScan(tchSignalingList, wb, headers);
		ResponseUtil.export(response, wb, "FSCAN数据" + FormatDate.formatDate() + ".xls");
	}

	/**
	 * 分页条件查询干扰告警记录
	 */
	@RequestMapping("/alarmhistory")
	public String Alarmhistory(@RequestParam(value = "page", required = false) String page, 
			@RequestParam(value = "rows", required = false) String rows, @RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime, 
		@RequestParam(value = "frontId", required = false) String frontId, @RequestParam(value = "interference_type", required = false) String interference_type, HttpServletResponse response) throws Exception {

		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();

		// 查询干扰前置机名获取
		if (frontId != null && !frontId.equals("")) {
			String[] subdistrict = frontId.split(",");
			String[] frontID = new String[subdistrict.length];
			
			for (int i = 0; i < subdistrict.length; i++) {
				if (subdistrict[i].trim().length() < 1) continue;
				map.put("frontId", subdistrict[i]);
				map.put("table_name","bs_info");
				frontID[i] = interferencequeryService.get_frontId(map);
			}
			List<String> subList = Arrays.asList(frontID);
			map.put("district", subList);
		}
		map.put("start", pageBean.getStart());
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", startTime);
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", endTime);
		}
		if (interference_type != null && !interference_type.equals("")) {
			map.put("interference_type", interference_type);
		}
		map.put("size", pageBean.getPageSize());
		List<AlarmHistory> alarmhistoryList = new ArrayList<AlarmHistory>();
		map.put("table_name", "history_alarm");

		List<AlarmHistory> sub_sdcchList = interferencequeryService.findalarmhistory(map);
		alarmhistoryList.addAll(sub_sdcchList);
		Long total = interferencequeryService.getTotalalarmhistory(map);

		JSONArray jsonArray1 = JSONArray.fromObject(alarmhistoryList);
		for (int i = jsonArray1.size() - 1; i >= 0; i--) {
			JSONObject json = new JSONObject();
			json = jsonArray1.getJSONObject(i);
			try {
				map.put("table_name", "interference_new");
				// alarmhistoryList.get(i).getFrontId();
				map.put("frontId", (String) json.get("frontId"));
				map.put("endTime", (String) json.get("timeStamp"));
				map.put("direction", (String) json.get("direction"));

				List<Interference> inteferencelist = interferencequeryService.findresult(map);
				if (inteferencelist.size() < 1) {
					total--;
					jsonArray1.remove(i);
					continue;
				}
				JSONArray tmp = JSONArray.fromObject(inteferencelist);
				jsonArray1.getJSONObject(i).putAll(tmp.getJSONObject(0));

				String str = "否";
				String Direction = "下行";
				Object timestart = json.get("timeBegin");
				Object timestamp = json.get("timeStamp");
				Object disposed = json.get("isDisposed");
				String timebegin = converttime((String) timestart);
				String time = converttime((String) timestamp);
				Object dir = json.get("direction");
				if (disposed.equals("1")) {
					str = "是";
				}
				if (dir.equals("0")) {
					Direction = "上行";
				}
				jsonArray1.getJSONObject(i).put("timeBegin", timebegin);
				jsonArray1.getJSONObject(i).put("timeStamp", time);
				jsonArray1.getJSONObject(i).put("isDisposed", str);
				jsonArray1.getJSONObject(i).put("direction", Direction);
			} catch (Exception e) {
				String str = "否";
				String Direction = "下行";
				Object timestamp = json.get("timeStamp");
				Object disposed = json.get("isDisposed");
				String time = converttime((String) timestamp);
				Object dir = json.get("direction");
				if (disposed.equals("1")) {
					str = "是";
				}
				if (dir.equals("0")) {
					Direction = "上行";
				}
				jsonArray1.getJSONObject(i).put("timeStamp", time);
				jsonArray1.getJSONObject(i).put("isDisposed", str);
				jsonArray1.getJSONObject(i).put("direction", Direction);
			}
        }  
		JSONObject result = new JSONObject();
		result.put("rows", jsonArray1);

		result.put("total", total);
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 查询所有前置机  单选下拉框用到
	 */
	@RequestMapping("/frontIdBox")
	public String groupComboListBox(HttpServletResponse response)throws Exception{
//		Map<String,Object> map = new HashMap<>();
//		JSONArray jsonArray=new JSONArray();
//		JSONObject jsonObject=new JSONObject();
//		//jsonObject.put("id", -1);
//		//jsonObject.put("name", "");
//		//jsonArray.add(jsonObject);
//		map.put("table_name","bs_info");
//		List<Integer> frontIdList=interferencequeryService.get_fs_front_ids(null);
//		for(int i=0;i<frontIdList.size();i++)
//		{
//			map.put("frontId",frontIdList.get(i));
//			String bs_name=interferencequeryService.get_bs_name(map);
//			if (bs_name == null || bs_name.length() < 1 || bs_name.equals("null")) continue;
//			jsonObject.put("name",bs_name);
//			jsonObject.put("text",bs_name);
//			jsonObject.put("id", i);
//			jsonArray.add(jsonObject);
//		}
//		ResponseUtil.write(response, jsonArray);
//		return null;
		Map<String,Object> map=new HashMap<String,Object>();
		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject=new JSONObject();

		JSONArray jsonArray1=new JSONArray();
		JSONObject jsonObject1=new JSONObject();

		//System.out.println("开始找sitename" );
		// jsonObject.put("id", -1);
		// jsonObject.put("name", "");
		// jsonArray.add(jsonObject);
		map.put("table_name","bs_info");
		List<String> bs_names=sdcchService.findDistricts(map);
		for(int i=0;i<bs_names.size();i++)
		{
			jsonObject.put("id", i);
			//String bs_name=alarmInfoService.get_bs_names();
			//System.out.println("bs_names:" + bs_names.get(i));
			jsonObject.put("name",bs_names.get(i));
			jsonObject.put("text", bs_names.get(i));
			System.out.println("小区："+bs_names.get(i));
			jsonArray.add(jsonObject);

		}
		System.out.println(jsonArray);
//		jsonObject1.put("id", 1000);
//		jsonObject1.put("name", "全选");
//		jsonObject1.put("text", "全选");
//		jsonObject1.put("children", jsonArray);
//		jsonArray1.add(jsonObject1);
		ResponseUtil.write(response, jsonArray);
		return null;
	}

	/**
	 * 查询所有前置机 多选 下拉框用到
	 */
	@RequestMapping("/frontId")
	public String groupComboList(HttpServletResponse response)throws Exception{
		Map<String,Object> map = new HashMap<>();
		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject=new JSONObject();
		
		JSONArray jsonArray1=new JSONArray();
		JSONObject jsonObject1=new JSONObject();
		
		//jsonObject.put("id", -1);
		//jsonObject.put("name", "");
		//jsonArray.add(jsonObject);
		map.put("table_name","bs_info");
		List<Integer> frontIdList=interferencequeryService.get_fs_front_ids(null);
		for(int i=0;i<frontIdList.size();i++)
		{
			map.put("frontId",frontIdList.get(i));
			String bs_name=interferencequeryService.get_bs_name(map);
			if (bs_name == null || bs_name.length() < 1 || bs_name.equals("null")) continue;
			jsonObject.put("name",bs_name);
			jsonObject.put("text",bs_name);
			jsonObject.put("id", i);
			jsonArray.add(jsonObject);
		}
		jsonObject1.put("id", 1000);
		jsonObject1.put("name", "全选");
		jsonObject1.put("text", "全选");
		jsonObject1.put("children", jsonArray);
		jsonArray1.add(jsonObject1);
		ResponseUtil.write(response, jsonArray1);
		return null;
	}
	
	/**
	 * 随机选择前置机用于显示频谱数据,用于频谱回放
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/fsfrontId")
	public String groupfrontId(@RequestParam(value="frontId",required=false)String frontId,HttpServletResponse response)throws Exception{
		String front_end_id;
		JSONObject jsonObject=new JSONObject();
		Map<String,Object> map=new HashMap<String,Object>();
		List<Integer> frontIdList=interferencequeryService.get_fs_front_ids(null);
	/*	jsonObject.put("frontId",frontIdList.get(0));*/
		if(frontId!=null&&!frontId.equals("")){
			map.put("frontId", frontId);
			map.put("table_name","bs_info");
			String front_Id=interferencequeryService.get_frontId(map);
			map.put("frontId", front_Id);
			front_end_id=front_Id;
		}
		else {
			map.put("frontId", frontIdList.get(0));
			front_end_id=Integer.toString(frontIdList.get(0));
		}
		map.put("table_name","fs_signal_overall");
		int largedate=interferencequeryService.get_largedate(map);
		int earlydate=interferencequeryService.get_earlydate(map);
		map.put("table_name","frequencySpectrum_" + front_end_id+"_"+largedate);
		long date=interferencequeryService.get_latestFSTime(map);
		map.put("table_name","frequencySpectrum_" + front_end_id+"_"+earlydate);
		long earlytime=interferencequeryService.get_earlyFSTime(map);
		String endTime=converttimesecond(String.valueOf(date));
		String startTime=converttimesecond(String.valueOf(earlytime));//提前1个小时
		jsonObject.put("startTime",startTime);
		jsonObject.put("endTime",endTime);
		ResponseUtil.write(response, jsonObject);
		return null;
	}
	/**
	 * 所有的干扰类型  下拉框用到
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/interferencelist")
	public String interferenceComboList(HttpServletResponse response)throws Exception{
		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject=new JSONObject();
		
		JSONArray jsonArray1=new JSONArray();
		JSONObject jsonObject1=new JSONObject();
		
//		jsonObject.put("id", -1);
//		jsonObject.put("name", "");
//		jsonArray.add(jsonObject);
		jsonObject.put("id", 0);
		jsonObject.put("name","TCH同邻频干扰");
		jsonObject.put("text","TCH同邻频干扰");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 1);
		jsonObject.put("name","BCCH同邻频干扰");
		jsonObject.put("text","BCCH同邻频干扰");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 2);
		jsonObject.put("name","阻塞或多径");
		jsonObject.put("text","阻塞或多径");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 3);
		jsonObject.put("name","互调干扰");
		jsonObject.put("text","互调干扰");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 4);
		jsonObject.put("name","杂散干扰");
		jsonObject.put("text","杂散干扰");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 5);
		jsonObject.put("name","其他类型干扰");
		jsonObject.put("text","其他类型干扰");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 6);
		jsonObject.put("name","测量报告-窄带干扰");
		jsonObject.put("text","测量报告-窄带干扰");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 7);
		jsonObject.put("name","外网强信号风险");
		jsonObject.put("text","外网强信号风险");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 8);
		jsonObject.put("name","外网翻频风险");
		jsonObject.put("text","外网翻频风险");
		jsonArray.add(jsonObject);
		
		jsonObject1.put("id",1000);
		jsonObject1.put("name", "全选");
		jsonObject1.put("text", "全选");
		jsonObject1.put("children", jsonArray);
		jsonArray1.add(jsonObject1);
		
		ResponseUtil.write(response, jsonArray1);
		return null;
	}
	
    public static String converttime(String s)
    {
    	if (s == null || s.length() < 1 || s.trim().length() < 1) return "";
    	String result;
    	SimpleDateFormat simpleDateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
		long It=new Long(s);
		Date date=new Date(It);
		result = simpleDateformat.format(date);
		return result;
    }
    
    public static String converttimesecond(String s)
    {
    	if (s == null || s.length() < 1 || s.trim().length() < 1) return "";
    	String result;
    	SimpleDateFormat simpleDateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long It=new Long(s);
		Date date=new Date(It);
		result = simpleDateformat.format(date);
		return result;
    }
    
    public static long timetoStamp(String s)
    {
    	if (s == null || s.length() < 1 || s.trim().length() < 1) return 0;
    	long result;
    	Date d = null;
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");  
        try {  
            d = sdf.parse(s);  
        } catch (ParseException pe) {  
            System.out.println(pe.getMessage());  
        }  
        result=d.getTime();       
        return result;
    }



	//修改干扰告警状态,标记为已处理
	@RequestMapping("/changealarmstatus")
	public String save(
			@RequestParam(value = "FIDs") String FIDs,
			@RequestParam(value = "DIRs") String DIRs,
			@RequestParam(value = "TIMS") String TIMs,
			HttpServletResponse response)throws Exception{
		int resultTotal=0; // 操作的记录条数
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("table_name", "history_alarm");
		String[] frontIDs = FIDs.split(",");
		String[] directions=DIRs.split(",");
		String[] timeStamps=TIMs.split(",");
		int dir;
		for (int i = 0; i < frontIDs.length; i++) {
			dir=0;
			if(directions[i].equals("下行")) {
				dir=1;
			}
			map.put("FrontId", frontIDs[i]);
			map.put("TimeStamp", timetoStamp(timeStamps[i]));
			map.put("Direction", dir);
			resultTotal=interferencequeryService.updatealarmhistory(map);
		}
		JSONObject result=new JSONObject();
		if(resultTotal>0){
			result.put("success", true);
		}else{
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	//修改干扰记录状态,标记为已处理
		@RequestMapping("/changeinterference")
		public String changeinterference(
				@RequestParam(value = "FIDs") String FIDs,
				@RequestParam(value = "DIRs") String DIRs,
				@RequestParam(value = "INFCs") String INFCs,
				@RequestParam(value = "INTS") String INTs,
				HttpServletResponse response)throws Exception{
			int resultTotal=0; // 操作的记录条数
			Map<String,Object> map=new HashMap<String,Object>();
			
			String[] frontIDs = FIDs.split(";");
			String[] directions=DIRs.split(";");
			String[] infChannels=INFCs.split(";"); //结束时间
			//String[] beginTimes=BTIMs.split(",");
			String[] interference_type=INTs.split(";");
			int dir;
			for (int i = 0; i < frontIDs.length; i++) {
				dir=0;
				if(directions[i].equals("下行")) {
					dir=1;
				}
				map.put("FrontId", frontIDs[i]);
				if(infChannels[i].equals("0")) {
					map.put("InfChannel", "");
				}
				else
					map.put("InfChannel", infChannels[i]);
				map.put("Direction", dir);
				map.put("InfType", interference_type[i]);
				map.put("ReleaseTime", System.currentTimeMillis());
				map.put("table_name", "interference_history");
				resultTotal=interferencequeryService.updateinterference_new(map);
				map.put("table_name", "interference_real_time");
				resultTotal=interferencequeryService.updateinterference_new(map)+resultTotal;
			}
			JSONObject result=new JSONObject();
			if(resultTotal>0){
				result.put("success", true);
			}else{
				result.put("success", false);
			}
			ResponseUtil.write(response, result);
			return null;
		}
	/**
	 * 获取当前的分析状态
	 */
	@RequestMapping("/Status")
	public String getStatus(HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		List<InfConfig> ConfigList = new ArrayList<InfConfig>();
		map.put("table_name","inf_config");
		List<InfConfig> sub_configList = interferencequeryService.get_Status(map);
		ConfigList.addAll(sub_configList);
		JSONObject result=new JSONObject();
		JSONObject json=new JSONObject(); 
		JSONArray jsonArray1=JSONArray.fromObject(ConfigList);
		json=jsonArray1.getJSONObject(0);
		result.put("id", json.get("id"));
		result.put("restart", json.get("restart"));
		result.put("status", json.get("status"));
		result.put("stopTime", json.get("stopTime"));
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 
	 * 改变Status的值
	 */
	@RequestMapping("/changedatabase")
	public String delete(@RequestParam(value="primaryKeys")String primaryKeys,HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		JSONObject result=new JSONObject();
		try {
			map.put("table_name", "inf_config");
			map.put("PrimaryKey", primaryKeys);
			interferencequeryService.changeDB(map);
			result.put("success", true);
		} catch (Exception e) {
			result.put("success", false);
			e.printStackTrace();
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 
	 *获取干扰分析参数
	 */
	@RequestMapping("/interferenceconfig")
	public String Interferenceconfig(HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		List<InfConfig> configList = new ArrayList<InfConfig>();
		map.put("table_name","inf_config");
		List<InfConfig> sub_configList = interferencequeryService.get_Status(map);
		configList.addAll(sub_configList);
		JSONArray jsonArray1=JSONArray.fromObject(configList); 
        JSONObject json=new JSONObject();  
        json=jsonArray1.getJSONObject(0);  
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("alarmConfig", json.get("alarmConfig"));
		jsonObject.put("infMinMinutes", json.get("infMinMinutes"));
		jsonObject.put("infMaxMinutes",json.get("infMaxMinutes"));
		jsonObject.put("minrxqual",json.get("minrxqual"));
		jsonObject.put("numofinfrxqual",json.get("numofinfrxqual"));
		jsonObject.put("minleisuretime",json.get("minleisuretime"));
		jsonObject.put("maxleisuretime",json.get("maxleisuretime"));
		jsonObject.put("NotKPSTCHthreshold",json.get("notKPSTCHthreshold"));
		jsonObject.put("KPSTCHthreshold",json.get("KPSTCHthreshold"));
		jsonObject.put("Onepointthreshold",json.get("onepointthreshold"));
		jsonObject.put("Otherchannelthreshold",json.get("otherchannelthreshold"));
		jsonObject.put("Servicelevel1",json.get("servicelevel1"));
		jsonObject.put("Servicelevel2",json.get("servicelevel2"));
		jsonObject.put("Servicelevel3",json.get("servicelevel3"));
		jsonObject.put("BCCH", json.get("BCCH"));
		jsonObject.put("TCH", json.get("TCH"));
		jsonObject.put("BLOCK", json.get("BLOCK"));
		jsonObject.put("INTERMODULATION", json.get("INTERMODULATION"));
		jsonObject.put("SPURIOUS", json.get("SPURIOUS"));
		jsonObject.put("OTHER", json.get("OTHER"));
		jsonObject.put("Minimumlevel",json.get("minimumlevel"));
		ResponseUtil.write(response, jsonObject);
		return null;
	}
	/**
	 * 
	 * 修改干扰分析参数
	 */
	@RequestMapping("/insertinfconfig")
	public void insertinfconfig(
			String InfMinMinutes, String InfMinMinutesOld,
			String InfMaxMinutes, String InfMaxMinutesOld,
			String Minrxqual, String MinrxqualOld,
			String Numofinfrxqual, String NumofinfrxqualOld,
			String Minleisuretime, String MinleisuretimeOld,
			String Maxleisuretime, String MaxleisuretimeOld,
			String NotKPSTCHthreshold, String NotKPSTCHthresholdOld,
			String KPSTCHthreshold, String KPSTCHthresholdOld,
			String Onepointthreshold, String OnepointthresholdOld,
			String Otherchannelthreshold, String OtherchannelthresholdOld,
			String Servicelevel1, String Servicelevel1Old,
			String Servicelevel2, String Servicelevel2Old,
			String Servicelevel3, String Servicelevel3Old,
			String Minimumlevel, String MinimumlevelOld,
			String BCCH, String BCCHOld,
			String TCH, String TCHOld, 
			String BLOCK, String BLOCKOld, 
			String INTERMODULATION, String INTERMODULATIONOld, 
			String SPURIOUS, String SPURIOUSOld, 
			String OTHER, String OTHEROld,
			HttpServletResponse response) throws Exception {
		int resultTotal = 0;
		JSONObject result = new JSONObject();
		Map<String,Object> map = new HashMap<>();
	    map.put("infMinMinutes", InfMinMinutes);
	    map.put("infMaxMinutes", InfMaxMinutes);
	    map.put("minrxqual", Minrxqual);
	    map.put("numofinfrxqual", Numofinfrxqual);
	    map.put("minleisuretime", Minleisuretime);
	    map.put("maxleisuretime", Maxleisuretime);
	    map.put("NotKPSTCHthreshold", NotKPSTCHthreshold);
	    map.put("KPSTCHthreshold", KPSTCHthreshold);
	    map.put("Onepointthreshold", Onepointthreshold);
	    map.put("Otherchannelthreshold", Otherchannelthreshold);
	    map.put("Servicelevel1", Servicelevel1);
	    map.put("Servicelevel2", Servicelevel2);
	    map.put("Servicelevel3", Servicelevel3);
	    map.put("Minimumlevel", Minimumlevel);
		map.put("BCCH", BCCH);
		map.put("TCH", TCH);
		map.put("BLOCK", BLOCK);
		map.put("INTERMODULATION", INTERMODULATION);
		map.put("SPURIOUS", SPURIOUS);
		map.put("OTHER", OTHER);
		map.put("table_name", "inf_config");
		resultTotal = interferencequeryService.saveinfconfig(map);
		if(resultTotal > 0){
			result.put("success", true);
			
			ArrayList<Map<String, Object>> sysoperationrecordList = new ArrayList<>();
			LinkedHashMap<String, Object> hm = new LinkedHashMap<>();
			hm.put("operateTime", System.currentTimeMillis());
			hm.put("userId", 1);
			hm.put("isImplemented", 1);
			hm.put("isSuccessful", 1);
			hm.put("operationType", 15);
			JSONObject jsonObject = new JSONObject();
			JSONObject jsonObjectOld = new JSONObject();
			
			if (!InfMinMinutes.equals(InfMinMinutesOld)) {
				jsonObject.put("InfMinMinutes", InfMinMinutes);
				jsonObjectOld.put("InfMinMinutesOld", InfMinMinutesOld);
			}
			if (!InfMaxMinutes.equals(InfMaxMinutesOld)) {
				jsonObject.put("InfMaxMinutes", InfMaxMinutes);
				jsonObjectOld.put("InfMaxMinutesOld", InfMaxMinutesOld);
			}
			if (!Minrxqual.equals(MinrxqualOld)) {
				jsonObject.put("Minrxqual", Minrxqual);
				jsonObjectOld.put("MinrxqualOld", MinrxqualOld);
			}
			if (!Numofinfrxqual.equals(NumofinfrxqualOld)) {
				jsonObject.put("Numofinfrxqual", Numofinfrxqual);
				jsonObjectOld.put("NumofinfrxqualOld", NumofinfrxqualOld);
			}
			if (!Minleisuretime.equals(MinleisuretimeOld)) {
				jsonObject.put("Minleisuretime", Minleisuretime);
				jsonObjectOld.put("MinleisuretimeOld", MinleisuretimeOld);
			}
			if (!NotKPSTCHthreshold.equals(NotKPSTCHthresholdOld)) {
				jsonObject.put("NotKPSTCHthreshold", NotKPSTCHthreshold);
				jsonObjectOld.put("NotKPSTCHthresholdOld", NotKPSTCHthresholdOld);
			}
			if (!KPSTCHthreshold.equals(KPSTCHthresholdOld)) {
				jsonObject.put("KPSTCHthreshold", KPSTCHthreshold);
				jsonObjectOld.put("KPSTCHthresholdOld", KPSTCHthresholdOld);
			}
			if (!Onepointthreshold.equals(OnepointthresholdOld)) {
				jsonObject.put("Onepointthreshold", Onepointthreshold);
				jsonObjectOld.put("OnepointthresholdOld", OnepointthresholdOld);
			}
			if (!Otherchannelthreshold.equals(OtherchannelthresholdOld)) {
				jsonObject.put("Otherchannelthreshold", Otherchannelthreshold);
				jsonObjectOld.put("OtherchannelthresholdOld", OtherchannelthresholdOld);
			}
			if (!Servicelevel1.equals(Servicelevel1Old)) {
				jsonObject.put("Servicelevel1", Servicelevel1);
				jsonObjectOld.put("Servicelevel1Old", Servicelevel1Old);
			}
			if (!Servicelevel2.equals(Servicelevel2Old)) {
				jsonObject.put("Servicelevel2", Servicelevel2);
				jsonObjectOld.put("Servicelevel2Old", Servicelevel2Old);
			}
			if (!Servicelevel3.equals(Servicelevel3Old)) {
				jsonObject.put("Servicelevel3", Servicelevel3);
				jsonObjectOld.put("Servicelevel3Old", Servicelevel3Old);
			}
			if (!Minimumlevel.equals(MinimumlevelOld)) {
				jsonObject.put("Minimumlevel", Minimumlevel);
				jsonObjectOld.put("MinimumlevelOld", MinimumlevelOld);
			}
			if (!BCCH.equals(BCCHOld)) {
				jsonObject.put("BCCH", BCCH);
				jsonObjectOld.put("BCCHOld", BCCHOld);
			}
			if (!TCH.equals(TCHOld)) {
				jsonObject.put("TCH", TCH);
				jsonObjectOld.put("TCHOld", TCHOld);
			}
			if (!BLOCK.equals(BLOCKOld)) {
				jsonObject.put("BLOCK", BLOCK);
				jsonObjectOld.put("BLOCKOld", BLOCKOld);
			}
			if (!INTERMODULATION.equals(INTERMODULATIONOld)) {
				jsonObject.put("INTERMODULATION", INTERMODULATION);
				jsonObjectOld.put("INTERMODULATIONOld", INTERMODULATIONOld);
			}
			if (!SPURIOUS.equals(SPURIOUSOld)) {
				jsonObject.put("SPURIOUS", SPURIOUS);
				jsonObjectOld.put("SPURIOUSOld", SPURIOUSOld);
			}
			if (!OTHER.equals(OTHEROld)) {
				jsonObject.put("OTHER", OTHER);
				jsonObjectOld.put("OTHEROld", OTHEROld);
			}
			
			hm.put("newValue", jsonObject.toString());
			hm.put("oldValue", jsonObjectOld.toString());
			
			sysoperationrecordList.add(hm);
			map.put("database_name", PropertityUtil.NETWORK_MANAGEMENT_DATABASE_NAME);
			map.put("list", sysoperationrecordList);
			sysOperationRecordService.add(map);
			
		}else{
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
	}
	
	/**
	 * 
	 * 修改AlarmConfig
	 */
	@RequestMapping("/insertalarmconfig")
	public void insertalarmconfig(String AlarmConfig, HttpServletResponse response)throws Exception{
		int resultTotal = 0;
		JSONObject result = new JSONObject();
		Map<String,Object> map = new HashMap<>();
	    map.put("alarmConfig", AlarmConfig);
	    System.out.println(AlarmConfig);
		map.put("table_name", "inf_config");
		resultTotal = interferencequeryService.savealarmconfig(map);
		if(resultTotal > 0){
			result.put("success", true);
			ArrayList<Map<String, Object>> sysoperationrecordList = new ArrayList<>();
			LinkedHashMap<String, Object> hm = new LinkedHashMap<>();
			hm.put("operateTime", System.currentTimeMillis());
			hm.put("userId", 1);
			hm.put("oldValue", null);
			hm.put("isImplemented", 1);
			hm.put("isSuccessful", 1);
			hm.put("operationType", 17);
			hm.put("newValue", AlarmConfig);
			sysoperationrecordList.add(hm);
			map.put("database_name", PropertityUtil.NETWORK_MANAGEMENT_DATABASE_NAME);
			map.put("list", sysoperationrecordList);
			sysOperationRecordService.add(map);
		} else {
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
	}
	
	/**
	 * 告警配置  下拉框用到
	 */
	@RequestMapping("/alarmvalue")
	public void alarmvalueComboList(HttpServletResponse response)throws Exception{
		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("id", -1);
		jsonObject.put("name", "");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 0);
		jsonObject.put("name","1");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 1);
		jsonObject.put("name","2");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 2);
		jsonObject.put("name","3");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 3);
		jsonObject.put("name","4");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 4);
		jsonObject.put("name","5");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 5);
		jsonObject.put("name","6");
		jsonArray.add(jsonObject);
		jsonObject.put("id", 6);
		jsonObject.put("name","7");
		jsonArray.add(jsonObject);
		ResponseUtil.write(response, jsonArray);
	}
	
	/*
	 * 用于手动计算互调干扰
	 */
	@RequestMapping("/calintermodu")
	public void Calintermodu(@RequestParam(value="state") String state, @RequestParam(value="channel") String channel,
			@RequestParam(value="infchannel") String infchannel, HttpServletResponse response)throws Exception{
		String Return = "";
		JSONObject ret=new JSONObject();
		Calintermodu calin= new Calintermodu();
        Return = calin.calintermodu(state, channel, infchannel);
		if (Return.isEmpty()) {
			ret.put("success", false);
		} else {
			ret.put("success", true);
			ret.put("value", Return);

			Map<String,Object> map = new HashMap<>();
			ArrayList<Map<String, Object>> sysoperationrecordList = new ArrayList<>();
			LinkedHashMap<String, Object> hm = new LinkedHashMap<>();
			hm.put("operateTime", System.currentTimeMillis());
			hm.put("userId", 1);
			hm.put("oldValue", null);
			hm.put("isImplemented", 1);
			hm.put("isSuccessful", 1);
			hm.put("operationType", 16);
			hm.put("newValue", Return);
			sysoperationrecordList.add(hm);
			map.put("database_name", PropertityUtil.NETWORK_MANAGEMENT_DATABASE_NAME);
			map.put("list", sysoperationrecordList);
			sysOperationRecordService.add(map);
		}
		ResponseUtil.write(response, ret);
	}
	
	/*
	 * 测量报告
	 */
	/**
	 * 分页条件查询干扰测量报告
	 */
	@RequestMapping("/measurementlist")
	public String Measurementlist(@RequestParam(value="page",required=false)String page,@RequestParam(value="rows",required=false)String rows,
			@RequestParam(value="startTime",required=false)String startTime,@RequestParam(value="endTime",required=false)String endTime,
			@RequestParam(value="frontId",required=false)String frontId,@RequestParam(value="direction",required=false)String direction,
			HttpServletResponse response)throws Exception{
		
		PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		Map<String,Object> map=new HashMap<String,Object>();
		//map.put("frontId", StringUtil.formatLike(StringUtil.formatLike(interference.getFrontId()))); // 查询干扰前置机名获取
		if(frontId!=null&&!frontId.equals("")){
			map.put("frontId", frontId);
		}
		if(direction!=null&&!direction.equals("")){
			map.put("direction", direction);
		}
		map.put("start", pageBean.getStart());
		if(startTime!=null&&!startTime.equals("NaN")){
			long tmp;
			tmp=timetoStamp(startTime);
			map.put("startTime", tmp);
		}
		if(endTime!=null&&!endTime.equals("NaN")){
			long tmp1;
			tmp1=timetoStamp(endTime);
			map.put("endTime", tmp1);
		}
		map.put("size", pageBean.getPageSize());
		List<InfMeasurement> interferenceList = new ArrayList<InfMeasurement>();
		map.put("table_name","inf_measurement");
		List<InfMeasurement> sub_sdcchList = interferencequeryService.findmeasurement(map);
		interferenceList.addAll(sub_sdcchList);
		Long total=interferencequeryService.getTotalinfmeasurement(map);
		JSONObject result=new JSONObject();
		JSONArray jsonArray=JSONArray.fromObject(interferenceList);
		for (int i = 0; i < jsonArray.size(); i++) {  
            JSONObject json=new JSONObject();  
            json=jsonArray.getJSONObject(i);  
            Object timestamp;
            Object dir;
            String start;
            String Direction="下行";
            timestamp=json.get("timeStamp");
            dir=json.get("direction");
            start=converttime((String)timestamp);
            if (dir.equals("0"))
            	Direction="上行";
            jsonArray.getJSONObject(i).put("timeStamp", start);
            jsonArray.getJSONObject(i).put("direction", Direction);
            
        }  
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 获取基站模型
	 * @param
	 * @param
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/bsmodellist")
	public String Bsmodellist(@RequestParam(value="frontId",required=false)String frontId,@RequestParam(value="direction",required=false)String direction,HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		if(frontId!=null&&!frontId.equals("")){
			map.put("frontId", frontId);
			map.put("table_name","bs_info");
			String front_Id=interferencequeryService.get_frontId(map);
			map.put("frontId", front_Id);
		}
		if(direction!=null&&!direction.equals("")){
			map.put("direction", direction);
		}
		List<BSModel> bsmodelList = new ArrayList<BSModel>();
		map.put("table_name","bs_model");
		List<BSModel> sub_bsmodelList = interferencequeryService.findbsmodel(map);
		bsmodelList.addAll(sub_bsmodelList);
		JSONObject result=new JSONObject();
		JSONArray jsonArray=JSONArray.fromObject(bsmodelList);
		result.put("rows", jsonArray);
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 获取基站模型
	 * @param
	 * @param
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/bsmodeltransitionlist")
	public String BsmodelTransitionlist(@RequestParam(value="frontId",required=false)String frontId,@RequestParam(value="direction",required=false)String direction,HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		if(frontId!=null&&!frontId.equals("")){
			map.put("frontId", frontId);
			map.put("table_name","bs_info");
			String front_Id=interferencequeryService.get_frontId(map);
			map.put("frontId", front_Id);
		}
		if(direction!=null&&!direction.equals("")){
			map.put("direction", direction);
		}
		List<BSModel> bsmodelList = new ArrayList<BSModel>();
		map.put("table_name","bs_model_transition");
		List<BSModel> sub_bsmodelList = interferencequeryService.findbsmodel(map);
		bsmodelList.addAll(sub_bsmodelList);
		JSONObject result=new JSONObject();
		JSONArray jsonArray=JSONArray.fromObject(bsmodelList);
		result.put("rows", jsonArray);
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 替换基站模型
	 * @param
	 * @param
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/replacebsmodel")
	public void ReplaceBsModel(@RequestParam(value="frontId",required=false)String frontId,@RequestParam(value="direction",required=false)String direction,@RequestParam(value="selectTime",required=false)String selectTime,HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		if(frontId!=null&&!frontId.equals("")){
			map.put("frontId", frontId);
			map.put("table_name","bs_info");
			String front_Id=interferencequeryService.get_frontId(map);
			map.put("frontId", front_Id);
		}
		JSONObject result=new JSONObject();
		int resulttotal=-1;
		if(direction.equals("0")&&selectTime.equals("0")) {
			resulttotal=interferencequeryService.replaceModelLeisureUp(map);
		}
		else if(direction.equals("1")&&selectTime.equals("0")) {
			resulttotal=interferencequeryService.replaceModelLeisureDown(map);
		}
		else if(direction.equals("0")&&selectTime.equals("1")) {
			resulttotal=interferencequeryService.replaceModelBusyUp(map);
		}
		else if(direction.equals("1")&&selectTime.equals("1")) {
			resulttotal=interferencequeryService.replaceModelBusyDown(map);
		}
		
		if(resulttotal>0) {
			result.put("success", true);
		}
		else {
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
	}
	
	/**
	 * 获取频谱
	 */
	@RequestMapping("/fslist")
	public String Fslist(@RequestParam(value="startTime",required=false)String startTime,@RequestParam(value="endTime",required=false)String endTime,@RequestParam(value="frontId",required=false)String frontId,@RequestParam(value="isAdjust",required=false)String isAdjust,
			@RequestParam(value="isfsreplay",required=false)String isfsreplay,HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		Map<String,Object> fscanmap=new HashMap<String,Object>();
		//long before = new Date().getTime();
		//long tmp=0;
		//long tmp1=0;
		String front_Id="";
		List<InfFrequencySpectrum> resultList = new ArrayList<>();
        List<InfFrequencySpectrum> tmpList1 = new ArrayList<>();
        List<InfFrequencySpectrum> tmpList2 = new ArrayList<>();
        List<FScan> fscanresultList = new ArrayList<>();
        List<FScan> fscantmpList1 = new ArrayList<>();
        List<FScan> fscantmpList2 = new ArrayList<>();
		if(frontId!=null&&!frontId.equals("")){
			map.put("frontId", frontId);
			map.put("table_name","bs_info");
			front_Id=interferencequeryService.get_frontId(map);
			map.put("frontId", front_Id);
			fscanmap.put("frontId", front_Id);
		}

		String time1 = "";
		String time2 = "";

		if(startTime!=null&&!startTime.equals("NaN")){
			//tmp=timetoStamp(startTime);
			map.put("startTime", startTime);
			fscanmap.put("startTime", startTime);
			time1 = returndate(Long.parseLong(startTime));
		}
		if(endTime!=null&&!endTime.equals("NaN")){
			//tmp1=timetoStamp(endTime);
			map.put("endTime", endTime);
			fscanmap.put("endTime", endTime);
			time2 = returndate(Long.parseLong(endTime));
		}

		if (time1.equals(time2) && time1.length() > 0) {
            map.put("table_name", "frequencySpectrum_"+ front_Id+"_"+time1);
            fscanmap.put("table_name", "fscan"+"_"+time1);
            resultList = interferencequeryService.findfs(map);
            try {
            	fscanresultList = interferencequeryService.getFScan(fscanmap);
            } catch(Exception e) {
            	e.printStackTrace();
            }
        }
        else{
            map.put("table_name", "frequencySpectrum_" + front_Id+"_"+time1);
            fscanmap.put("table_name", "fscan_" +time1);
            tmpList1 = interferencequeryService.findmorethanfs(map);
            resultList.addAll(tmpList1);
            try {
            	fscantmpList1 = interferencequeryService.getFScan(fscanmap);
            	fscanresultList.addAll(fscantmpList1);
            } catch(Exception e) {
            	e.printStackTrace();
            }
            map.put("table_name", "FrequencySpectrum_" + front_Id+"_"+time2);
            tmpList2 = interferencequeryService.findlessthanfs(map);
            resultList.addAll(tmpList2);
            fscanmap.put("table_name", "fscan_" +time2);
            try {
            	fscantmpList2 = interferencequeryService.getFScan(fscanmap);
                fscanresultList.addAll(fscantmpList2); 
            } catch(Exception e) {
            	e.printStackTrace();
            }
        }
		
		for (int i = 0; i < fscanresultList.size() - 1; i++) {
			for (int j = fscanresultList.size() - 1; j > i; j--) {
				if (fscanresultList.get(j).getLAC().equals(fscanresultList.get(i).getLAC()) &&
						fscanresultList.get(j).getCID().equals(fscanresultList.get(i).getCID())) {
					fscanresultList.remove(j);
				}
			}
		}
		JSONObject result=new JSONObject();
		JSONArray jsonArray=JSONArray.fromObject(resultList);
		JSONArray jsonArray1=JSONArray.fromObject(resultList);
		JSONArray fscanjsonArray=JSONArray.fromObject(fscanresultList);
		//long t = new Date().getTime();
		//System.out.println("haha1:"+(t-t2));
		String returnmessageup="";
		String returnmessagedown="";
		for (int i = 0; i < jsonArray.size(); i++) {  
			double[][] messagedown=new double[5][4];
			double[][] messageup=new double[5][4];
            JSONObject json=new JSONObject();  
            json=jsonArray.getJSONObject(i);  
            Object rawmessage;
            double[] fsData=null;
            double[] fsDataDown=null;
            double[] fsDataUp=null;
            rawmessage=json.get("rawMessage");
            if(isAdjust.equals("0")) {
                fsData = fsRawTodBm(rawmessage.toString());//转化成下上行441*2点
                fsDataDown = Arrays.copyOfRange(fsData, 0, 441);
                fsDataUp = Arrays.copyOfRange(fsData, 441, 441 * 2);
                if(isfsreplay.equals("1")) {
                	messagedown=searchmaxvalues(dealwithdouble(fsDataDown),0,1);
                    messageup=searchmaxvalues(dealwithdouble(fsDataUp),0,0);
                    returnmessageup=getmessage(messageup);
                    returnmessagedown=getmessage(messagedown);
                }
                
            }
            else {
            	fsData = fsRawTodBmadjust(rawmessage.toString());//转化成下上行441*2点
            	//System.out.println(fsData.length);
                fsDataDown = Arrays.copyOfRange(fsData, 0, 2625);
                fsDataUp = Arrays.copyOfRange(fsData, 2625, 2625 * 2);
                if(isfsreplay.equals("1")) {
                	messagedown=searchmaxvalues(dealwithdouble(fsDataDown),1,1);
                    messageup=searchmaxvalues(dealwithdouble(fsDataUp),1,0);
                    returnmessageup=getmessage(messageup);
                    returnmessagedown=getmessage(messagedown);
                } 
            }
            if(isfsreplay.equals("1")) {
            	jsonArray.getJSONObject(i).put("pole", returnmessagedown); //down
                jsonArray1.getJSONObject(i).put("pole", returnmessageup);
            }
            jsonArray.getJSONObject(i).put("rawMessage", fsArrayToString(fsDataDown));
            jsonArray1.getJSONObject(i).put("rawMessage", fsArrayToString(fsDataUp));
        }  
		result.put("rows", jsonArray);  //下行
		result.put("rows1", jsonArray1); //上行
		result.put("fscan", fscanjsonArray);
		result.put("success", true);
		//long end = new Date().getTime();
        //System.out.println("haha:"+(end-t));
		ResponseUtil.write(response, result);
		return null;
	}
	
	/*
	 * 求最大极点的函数
	 */
	public double[][] searchmaxvalues(double[] data,int status,int direction){
		double[][] result=new double[5][4];  //第1个为频谱值，第2个为location，第3对应的频率，第4 个为channel
		double[][] tmpresult=new double[21][4];
		double[][] tmpresult1=new double[125][4];
		double[][] fivevalues=new double[5][4];;
		double[] tmp=new double[21];
		double[] tmpdata=new double[21];
		double maxdata;
		double location;
		int length=data.length;
		DecimalFormat df1 = new DecimalFormat("#.0");
		/*
		 * status=0表示GSM-R频段内的计算，status=1表示调整频率后的计算
		 */
		int sum=0;
		if(status==0) {
			for(int i=0;i<length;i=i+21) {
				System.arraycopy(data, i, tmp, 0, 21);
				System.arraycopy(tmp, 0, tmpdata, 0, 21); //用于保存原始数据，来取得位置
				Arrays.sort(tmp);
				maxdata=tmp[20];
				location=getposition(tmpdata, maxdata);
				tmpresult[sum][0]=maxdata;
				tmpresult[sum][1]=location+sum*21;
				if(direction==0)//上行
				{
					tmpresult[sum][2]=885.0+sum*0.2;   //取中心频率
					tmpresult[sum][2]=Double.valueOf(df1.format(tmpresult[sum][2]));
					tmpresult[sum][3]=getChannel(tmpresult[sum][2]);
				}
				else {  //下行
					tmpresult[sum][2]=930.0+sum*0.2;
					tmpresult[sum][2]=Double.valueOf(df1.format(tmpresult[sum][2]));
					tmpresult[sum][3]=getChanneldown(tmpresult[sum][2]);
				}
				sum++;
			}
			fivevalues=searchfivemaxvalues(tmpresult,0);
			for(int j=0;j<5;j++) {
				System.arraycopy(fivevalues[j], 0, result[j],0, 4);
			}
		}
		else {
			for(int i=0;i<length;i=i+21) {
				System.arraycopy(data, i, tmp, 0, 21);
				System.arraycopy(tmp, 0, tmpdata, 0, 21); //用于保存原始数据，来取得位置
				Arrays.sort(tmp);
				maxdata=tmp[20];
				location=getposition(tmpdata, maxdata);
				tmpresult1[sum][0]=maxdata;
				tmpresult1[sum][1]=location+sum*21;
				if(direction==0)//上行
				{
					tmpresult1[sum][2]=884.6-5+sum*0.2;  //上行左移5MHz
					tmpresult1[sum][2]=Double.valueOf(df1.format(tmpresult1[sum][2]));
					tmpresult1[sum][3]=getChannel(tmpresult1[sum][2]);
				}
				else {  //下行
					tmpresult1[sum][2]=929.6+sum*0.2;
					tmpresult1[sum][2]=Double.valueOf(df1.format(tmpresult1[sum][2]));
					tmpresult1[sum][3]=getChanneldown(tmpresult1[sum][2]);
				}
				sum++;
			}
			fivevalues=searchfivemaxvalues(tmpresult1,1);
			for(int j=0;j<5;j++) {
				System.arraycopy(fivevalues[j], 0, result[j],0, 4);
			}
		}
		return result;
	}
	
	/*
	 * double数组保留1位
	 *
	 */
	public double[] dealwithdouble(double[] data) {
		double[] result=new double[data.length];
		DecimalFormat df = new DecimalFormat("#.0");
		for(int i=0;i<data.length;i++) {
			try {
				result[i]=Double.valueOf(df.format(data[i]));
			}catch(NumberFormatException e) {
				result[i]=-140.0;
			}
			
		}
		return result;
		}

	/*
	 * 判断前五个最大值
	 */
	public double[][] searchfivemaxvalues(double[][] data,int status){
		double[][] tmpresult=new double[5][4];
		double[] tmp=new double[21];
		double[] location=new double[21];
		double[] frequency=new double[21];
		double[] channel=new double[21];
		double[] tmpdata=new double[21];
		double[] tmp1=new double[125];
		double[] location1=new double[125];
		double[] tmpdata1=new double[125];
		double[] frequency1=new double[125];
		double[] channel1=new double[125];
		int l;
		double maxdata;
		int length=data.length;
		int sum=0;
		if(status==0) {
			for(int i=0;i<length;i=i+1) {
				tmp[i]=data[i][0];
				location[i]=data[i][1];
				frequency[i]=data[i][2];
			    channel[i]=data[i][3];
			}
			System.arraycopy(tmp, 0, tmpdata, 0, length); //用于保存原始数据，来取得位置
			Arrays.sort(tmp);
			for(int j=0;j<5;j++) {
				maxdata=tmp[length-1-j];
				l=getposition(tmpdata, maxdata);
				tmpresult[sum][0]=maxdata;
				tmpresult[sum][1]=location[l];
				tmpresult[sum][2]=frequency[l];
				tmpresult[sum][3]=channel[l];
				sum++;
			}
		}
		else {
			for(int i=0;i<length;i=i+1) {
				tmp1[i]=data[i][0];
				location1[i]=data[i][1];
				frequency1[i]=data[i][2];
			    channel1[i]=data[i][3];
			}
			System.arraycopy(tmp1, 0, tmpdata1, 0, length); //用于保存原始数据，来取得位置
			Arrays.sort(tmp1);
			for(int j=0;j<5;j++) {
				maxdata=tmp1[length-1-j];
				l=getposition(tmpdata1, maxdata);
				tmpresult[sum][0]=maxdata;
				tmpresult[sum][1]=location1[l];
				tmpresult[sum][2]=frequency1[l];
				tmpresult[sum][3]=channel1[l];
				sum++;
			}
		}
		return tmpresult;
	}
	public int getChannel(double freq) {
        int leftBound = 885*10;
        int freqInt = (int)Math.round(freq *  10);//为了解决0.2的计算不精确的问题
        int cnt = (freqInt - leftBound)/2;
//        System.out.println("2的" + cnt + "倍");
        int result = 999 + cnt;
//        System.out.println("频道：" + result);
        return result % 1024;
    }
    public int getChanneldown(double freq) {
        int leftBound = 930*10;
        int freqInt = (int)Math.round(freq *  10);//为了解决0.2的计算不精确的问题
        int cnt = (freqInt - leftBound)/2;
//        System.out.println("2的" + cnt + "倍");
        int result = 999 + cnt;
//        System.out.println("频道：" + result);
        return result % 1024;
    }
    
    public String getmessage(double[][] data) {
    	DecimalFormat df1 = new DecimalFormat("#.0");
    	String result="最大的五个极点:\n";
    	DecimalFormat df=new DecimalFormat("0000");
    	for(int i=0;i<5;i++) {
    		result=result+(i+1)+": "+Double.valueOf(df1.format(data[i][2]))+"MHz     CH"+df.format((int)data[i][3])+"     "+Double.valueOf(df1.format(data[i][0]))+"dBm          ";
    		if(i==1||i==3) {
    			result=result+"\n";
    		}
    	}
    	return result;
    }
    
    /*
     * 查找某个数在数组中出现的位置
     */
    public int getposition(double[] data,double search) {
    	int result=0;
    	for(int i=0;i<data.length;i++) {
    		if(data[i]==search) {
    			result=i;
    			return result;
    		}
    	}
    	return result;
    }
    
    /*
     * 实时频谱的处理函数
     */
    /**
	 * 获取频谱
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/fsmonitor")
	public String Fsmonitor(@RequestParam(value="startTime",required=false)String startTime,
			@RequestParam(value="frontId",required=false)String frontId,
			@RequestParam(value="isAdjust",required=false)String isAdjust,HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		//long before = new Date().getTime();
		//long tmp=0;
		//long tmp1=0;
		String front_Id="";
		JSONObject result=new JSONObject();
		List<InfFrequencySpectrum> resultList = new ArrayList<InfFrequencySpectrum>();
		List<InfFrequencySpectrum> resultList1 = new ArrayList<InfFrequencySpectrum>();
		List<InfFrequencySpectrum> resultList2 = new ArrayList<InfFrequencySpectrum>();
		
		if(frontId!=null&&!frontId.equals("")){
			map.put("frontId", frontId);
			map.put("table_name","bs_info");
			front_Id=interferencequeryService.get_frontId(map);
//			front_Id="57111000";
			map.put("frontId", front_Id);
		}
		
	//		startTime="1588128533000";
		List<FScan> fscan = null;
		if(startTime!=null&&!startTime.equals("NaN")){
			
			Long preStartTime = Long.parseLong(startTime) - 50000;
	        Map<String, String> fscanmap = new HashMap<>();
	        
			fscanmap.put("startTime", preStartTime.toString());
			fscanmap.put("endTime", startTime);
			fscanmap.put("frontId", front_Id);
			//System.out.println("front_Id: " + front_Id);
			//fscanmap.put("frontId", "450571013");
			String time1 = returndate(Long.parseLong(startTime));
			fscanmap.put("table_name", "fscan"+"_"+time1);
			///////////////////////////////////////////////////////////////////////////
			try {
				fscan = interferencequeryService.getFScan(fscanmap);
				for (int i = 0; i < fscan.size() - 1; i++) {
					for (int j = fscan.size() - 1; j > i; j--) {
						if (fscan.get(j).getLAC().equals(fscan.get(i).getLAC()) && fscan.get(j).getCID().equals(fscan.get(i).getCID())) {
							fscan.remove(j);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
		if(startTime!=null&&!startTime.equals("NaN")){
			//tmp=timetoStamp(startTime);
			map.put("startTime", startTime);
			//map.put("startTime", "1542515811000");
		}
		map.put("size", 2);
		int length=0;
		String time1=returndate(Long.parseLong(startTime));
		String time2=returndate(Long.parseLong(startTime)-24*60*60*1000);
        map.put("table_name", "frequencySpectrum_"+ front_Id+"_"+time1);
        try {
             resultList1 = interferencequeryService.findfsmonitor(map);
             length=resultList1.size();
             resultList.addAll(resultList1);
        }catch(Exception e) {
        }
        if(length<2) {
        	try {
        		map.put("size", 2-length);
        		map.put("table_name", "frequencySpectrum_"+ front_Id+"_"+time2);
                resultList2 = interferencequeryService.findfsmonitor(map);
                length=length+resultList2.size();
                resultList.addAll(resultList2);
           }catch(Exception e) {
           }
        }
        if(length<2) {
        	result.put("success", false);
        	ResponseUtil.write(response, result);
        	return null;
        }
        
		JSONArray jsonArray=JSONArray.fromObject(resultList);
		double[] fsData1=null;
        double[] fsDataDown1=null;
        double[] fsDataUp1=null;
        double[] fsData2=null;
        double[] fsDataDown2=null;
        double[] fsDataUp2=null;
        long time=0;
        JSONObject json1=new JSONObject();  
        json1=jsonArray.getJSONObject(0);  
        Object rawmessage1;
        rawmessage1=json1.get("rawMessage");
        time=json1.getLong("timeStamp");
        JSONObject json2=new JSONObject();  
        json2=jsonArray.getJSONObject(1);  
        Object rawmessage2;
        rawmessage2=json2.get("rawMessage");
        if(isAdjust.equals("0")) {
             fsData1 = fsRawTodBm(rawmessage1.toString());//转化成下上行441*2点
             fsDataDown1 = Arrays.copyOfRange(fsData1, 0, 441);
             fsDataUp1 = Arrays.copyOfRange(fsData1, 441, 441 * 2);
             fsData2 = fsRawTodBm(rawmessage2.toString());//转化成下上行441*2点
             fsDataDown2 = Arrays.copyOfRange(fsData2, 0, 441);
             fsDataUp2 = Arrays.copyOfRange(fsData2, 441, 441 * 2);
                
       }
       else {
            fsData1 = fsRawTodBmadjust(rawmessage1.toString());//转化成下上行441*2点
            fsDataDown1 = Arrays.copyOfRange(fsData1, 0, 2625);
            fsDataUp1 = Arrays.copyOfRange(fsData1, 2625, 2625 * 2);
            fsData2 = fsRawTodBmadjust(rawmessage2.toString());//转化成下上行441*2点
            fsDataDown2 = Arrays.copyOfRange(fsData2, 0, 2625);
            fsDataUp2 = Arrays.copyOfRange(fsData2, 2625, 2625 * 2);
       }
       JSONArray Down=new JSONArray();  
       JSONArray Up=new JSONArray();
       JSONObject tmpdown=new JSONObject();
       JSONObject tmpup=new JSONObject();
       double[][] dataDown=getresult(fsDataDown2,fsDataDown1);
       double[][] dataUp=getresult(fsDataUp2,fsDataUp1);
       int Length=fsDataDown1.length;
       double[] datadown=new double[Length];
       double[] dataup=new double[Length];
       String returnmessageup="";
       String returnmessagedown="";
       double[][] messagedown=new double[5][4];
       double[][] messageup=new double[5][4];
        for (int j=0;j<5;j++) {
        	System.arraycopy(dataDown[j], 0, datadown,0, Length);
        	System.arraycopy(dataUp[j], 0, dataup,0, Length);
        	if(isAdjust.equals("0")) {
        		messagedown=searchmaxvalues(dealwithdouble(datadown),0,1);
                messageup=searchmaxvalues(dealwithdouble(dataup),0,0);
                returnmessageup=getmessage(messageup);
                returnmessagedown=getmessage(messagedown);
        	}
        	else {
        		messagedown=searchmaxvalues(dealwithdouble(datadown),1,1);
                messageup=searchmaxvalues(dealwithdouble(dataup),1,0);
                returnmessageup=getmessage(messageup);
                returnmessagedown=getmessage(messagedown);
        	}
        	tmpdown.put("rawMessage", fsArrayToString(datadown));
        	tmpup.put("rawMessage",fsArrayToString(dataup));
        	tmpdown.put("pole", returnmessagedown); //down
        	tmpup.put("pole", returnmessageup);
        	Down.add(tmpdown);
        	Up.add(tmpup);
        }  
        
        
        
		result.put("Down", Down);  //下行
		result.put("Up", Up); //上行
		result.put("time", time);
		result.put("fscan", fscan);
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}
	 
	public double[][] getresult(double[] data1,double[] data2){
		double[][] result=new double[5][data1.length];
		for(int i=0;i<data1.length;i++) {
			result[0][i]=data1[i]+0.2*(data2[i]-data1[i]);
			result[1][i]=data1[i]+0.4*(data2[i]-data1[i]);
			result[2][i]=data1[i]+0.6*(data2[i]-data1[i]);
			result[3][i]=data1[i]+0.8*(data2[i]-data1[i]);
			result[4][i]=data2[i];
		}
		return result;
	}
	/**
	 * 
	 * @param
	 * @param
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/gettch")
	public String GetTCH(@RequestParam(value="frontId",required=false)String frontId, @RequestParam(value="startTime",required=false)String startTime, @RequestParam(value="endTime",required=false)String endTime, @RequestParam(value="infType",required=false)String infType, HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		if(frontId!=null&&!frontId.equals("")){
			map.put("frontId", frontId);
			map.put("table_name","bs_info");
			String front_Id=interferencequeryService.get_frontId(map);
			map.put("frontId", front_Id);
		}
		//公网工参数据
		String BCCH;
		String TCH1;
		String TCH2;
		String TCH3;
		String TCH;
		String LAC;
		String CI;
		map.put("table_name","bs_info");
		BCCH = interferencequeryService.get_bcch(map);
		TCH1 = interferencequeryService.get_tch1(map);
		TCH2 = interferencequeryService.get_tch2(map);
		TCH3 = interferencequeryService.get_tch3(map);
		LAC = interferencequeryService.get_lac(map);
		CI = interferencequeryService.get_ci(map);
		TCH=TCH1;
		if(TCH2!=null) {
			TCH=TCH+"、"+TCH2;
		}
		if(TCH3!=null) {
			TCH=TCH+"、"+TCH3;
		}
		JSONObject result=new JSONObject();
		result.put("BCCH", BCCH);
		result.put("TCH", TCH);
		result.put("LAC", LAC);
		result.put("CI", CI);
		//扫频数据
		System.out.println("infType="+infType);
		if(infType.equals("外网强信号风险") || infType.equals("外网翻频风险")) {
			String time = "";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
			long startTimeLong = 0;
			long endTimeLong = 0;
	        try {
	            startTimeLong = sdf.parse(startTime).getTime();
	            endTimeLong = sdf.parse(endTime).getTime();
	            System.out.print("startTimeLong:"+startTimeLong);
	            System.out.print("endTimeLong:"+endTimeLong);
	        }catch (ParseException e){
	            e.printStackTrace();
	        }
			time = returndate(startTimeLong);
			map.put("table_name", "fscan_"+time);
			map.put("startTime", startTimeLong);
			map.put("endTime", endTimeLong);
			List<FScan> scans = new ArrayList<>();
			try {
		        scans = interferencequeryService.getFScan(map);
			}catch(Exception e)
	        {
	            System.out.println("数据库语法错误异常："+e);
	        }
			System.out.println("ScanTime="+scans.get(0).getScanTime());
			result.put("LAC1", scans.get(0).getLAC());
			result.put("CI1", scans.get(0).getCID());
			result.put("BCCH1", scans.get(0).getBCCH());
			result.put("TRXs", scans.get(0).getTRXs());
			result.put("MCC", scans.get(0).getMCC());
			result.put("MNC", scans.get(0).getMNC());
			result.put("RXLEV", scans.get(0).getRXLEV());
		}
		else {
			result.put("LAC1", "");
			result.put("CI1", "");
			result.put("BCCH1", "");
			result.put("TRXs", "");
			result.put("MCC", "");
			result.put("MNC", "");
			result.put("RXLEV", "");
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	/*
	 * 频谱函数
	 */
	//获取年月日
    public static String returndate(long time) {
        Date date = new Date(time);
		int ii=date.getYear()+1900; //获取年份
		//System.out.println(ii);
		int i1=date.getMonth()+1;  //获取月份between 0 and 11
	    int i2=date.getDate(); //获取日期
	    String s1="";
	    if(i2<10)
	        s1="0"+i2;
		else
	        s1=""+i2;
		
		String s="";
		if(i1<10)
	        s=s+ii+"0"+i1+s1;
		else
	        s=s+ii+i1+s1;
	    return s;
    }
    
    /**
     * 将rawMessage转换成dBm的值
     * @param fsString
     * @return 
     */
    public static double[] fsRawTodBm(String fsString) {
        double[] result = jsonToArray(fsString);
        int size = 441;
        for(int i = 0; i < size; i++) {
            //下行
            result[i] = 20.0 * Math.log10(result[i]);
            result[i] = result[i] -133 -30;
            //上行
            result[i + size] = 20.0 * Math.log10(result[i + size]);
            result[i + size] = result[i + size] -135 -30;
        } 
        return result;
    }
    
    /**
     * 将从gsmr数据库中取出的频谱字符串转为GSM-R频谱范围
     * @param s
     * @return 
     */
    public static double[] jsonToArray(String s) {
        double[] result = new double[441 * 2];//有用频谱上下行各441点  各4M
        int index = 0;
        JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(s);
        JSONArray jsonArray = jsonObj.getJSONArray("Data");
        for(int i = 777; i < 1218; i++) {//下行441点
            result[index++] = jsonArray.getDouble(i);
        }
        for(int i = 4096+777+525; i < 4096+1218+525; i++) {//上行441点
            result[index++] = jsonArray.getDouble(i);
        }
        return result;
    }
    
    /**
     * 将rawMessage转换成dBm的值
     * @param fsString
     * @return 
     */
    public static double[] fsRawTodBmadjust(String fsString) {
        double[] result = jsonToArrayadjust(fsString);
        int size = 2625;
        for(int i = 0; i < size; i++) {
            //下行
            result[i] = 20.0 * Math.log10(result[i]);
            result[i] = result[i] -133 -30;
            //上行
            result[i + size] = 20.0 * Math.log10(result[i + size]);
            result[i + size] = result[i + size] -135 -30;
        } 
        return result;
    }
    
    /**
     * 将从gsmr数据库中取出的频谱字符串转为GSM-R频谱范围
     * @param s
     * @return 
     */
    public static double[] jsonToArrayadjust(String s) {
        double[] result = new double[2625 * 2];//有用频谱上下行各2625点  
        int index = 0;
        JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(s);
        JSONArray jsonArray = jsonObj.getJSONArray("Data");
        for(int i = 735; i < 3360; i++) {//下行441点
            result[index++] = jsonArray.getDouble(i);
        }
        for(int i = 4096+735; i < 4096+3360; i++) {//上行441点
            result[index++] = jsonArray.getDouble(i);
        }
        return result;
    }
    
    /**
     * 将频谱数据转为存在数据库中的字符串
     * @param fsData
     * @return 
     */
    public static String fsArrayToString(double[] fsData) {
        StringBuilder sb = new StringBuilder();
        DecimalFormat decimalFormat = new DecimalFormat("###.000000");
        for(int i = 0; i < fsData.length; i++) {
            sb.append(decimalFormat.format(fsData[i]));
            sb.append(",");
        }
        if(sb.length() > 0)
            sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
    
    
    /*
     * 离线获取前置机经纬度以及对应基站的经纬度
     */
    /**
	 * 
	 * @param
	 * @param
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/bsstation")
	public String BSStation(@RequestParam(value = "frontId", required = false) String frontId, @RequestParam(value = "piontType", required = false) String piontType, HttpServletResponse response) throws Exception {
		Map<String,Object> map=new HashMap<String,Object>();
		System.out.println(piontType);
		String[] fId=null;
		if (frontId == null || frontId.equals("")) {
			System.out.println("没选前置机号");
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("table_name", "bs_info");
			List<Integer> turnUse = interferencequeryService.get_fs_front_ids(null);
			for (int i = 0; i < turnUse.size(); i++) {
				map1.put("frontId", turnUse.get(i));
				String bs_name = interferencequeryService.get_bs_name(map1);
				if (bs_name == null || bs_name.length() < 1 || bs_name.equals("null")) continue;
				frontId = frontId + "," + bs_name;
			}
			frontId = frontId.substring(1);
			System.out.println(frontId);
		}
		System.out.println("frontId:"+frontId);
		if(frontId!=null&&!frontId.equals("")){
		    fId=frontId.split(",");
		}
		System.out.println("fId:"+fId[0]+":::"+fId[1]);
		JSONArray frontIdInfo=new JSONArray();
		JSONArray bsStationInfo=new JSONArray();
		JSONArray rsStationInfo = new JSONArray();
		JSONArray unsettledFrontIdInfo = new JSONArray();
		JSONArray historyInterferenceInfo = new JSONArray();
		List<BS_station> bsStationList = new ArrayList<BS_station>();
		List<Integer> interferenceFrontId = interferencequeryService.getInterferenceCondition();
		System.out.println(interferenceFrontId.toString());
		if (frontId != null && !frontId.equals("")) {
			for (int i = 0; i < fId.length; i++) {
				if (!fId[i].equals("")) {
					map.put("frontId", fId[i]);
					map.put("table_name", "bs_info");
					String front_Id = interferencequeryService.get_frontId(map);
					map.put("frontId", front_Id);
					if (piontType.contains("前置机")) {
						BS_info currentBsinfo = interferencequeryService.getbsinfo(map);
						frontIdInfo.add(currentBsinfo);
					}
					if (interferenceFrontId.contains(Integer.valueOf(front_Id))) {
						long nowTime = System.currentTimeMillis();
						long TimeBegin = nowTime - (nowTime + TimeZone.getDefault().getRawOffset()) % (1000 * 3600 * 24);
						map.put("TimeBegin", TimeBegin);
						System.out.println(TimeBegin);
						List<Interference> interferenceList = new ArrayList<Interference>();
						interferenceList = interferencequeryService.getInterference(map);
						unsettledFrontIdInfo.add(interferenceList);
					}

					// map.put("table_name", "bs_station");
					// List<BS_station> bsStationList = new
					// ArrayList<BS_station>();
					// if (piontType.contains("移动基站")) {
					// map.put("MNC", "0");
					// bsStationList =
					// interferencequeryService.getbsstation(map);
					// bsStationInfo.add(bsStationList);
					// }
					// if (piontType.contains("联通基站")) {
					// System.out.println("联通基站");
					// map.put("MNC", "1");
					// bsStationList =
					// interferencequeryService.getbsstation(map);
					// bsStationInfo.add(bsStationList);
					// System.out.println(bsStationInfo);
					// }
				}
			}
		}
		map.put("table_name", "bs_station");
		if (piontType.contains("移动基站")) {
			map.put("MNC", 0);
			bsStationList = interferencequeryService.getbsstation(map);
			bsStationInfo.add(bsStationList);
		}
		if (piontType.contains("联通基站")) {
			System.out.println("联通基站");
			map.put("MNC", 1);
			bsStationList = interferencequeryService.getbsstation(map);
			bsStationInfo.add(bsStationList);
			System.out.println(bsStationInfo);
		}
		List<RS_station> rsStationList = new ArrayList<RS_station>();

		List<InfHistorySource> historySourceList = new ArrayList<InfHistorySource>();
		if (piontType.contains("车站")) {

			map.put("table_name", "rs_station");
			rsStationList = interferencequeryService.getrsstation(map);
			rsStationInfo.add(rsStationList);
		}
		if (piontType.contains("历史干扰源")) {
			DecimalFormat df = new DecimalFormat(".00000000");
			historySourceList = interferencequeryService.getInfHistorySource(map);
			for (int j = 0; j < historySourceList.size(); j++) {

				String[] s1 = historySourceList.get(j).getSourcePosition().split("北，");
				String[] s2 = s1[1].split("东");
				String[] s3 = s1[0].split("°");
				String[] s4 = s3[1].split("'");
				String[] s5 = s4[1].split("\"");
				String target1 = s4[0].trim();
				String target2 = s5[0].trim();
				Double tar1 = Double.parseDouble(target1) / 60;
				Double tar2 = Double.parseDouble(target2) / 3600;
				Double tar_1 = tar1 + tar2;
				String lon = s3[0].trim() + df.format(tar_1);

				String[] s6 = s2[0].split("°");
				String[] s7 = s6[1].split("'");
				String[] s8 = s7[1].split("\"");
				String target3 = s7[0].trim();
				String target4 = s8[0].trim();
				// System.out.println(target3);
				// System.out.println(target4);
				Double tar3 = Double.parseDouble(target3) / 60;
				Double tar4 = Double.parseDouble(target4) / 3600;
				Double tar_2 = tar3 + tar4;
				String lat = s6[0].trim() + df.format(tar_2);

				InfHistorySource h = new InfHistorySource();
				h = historySourceList.get(j);
				h.setSourcePosition(lat + "," + lon);
				historySourceList.set(j, h);
				// System.out.println(s1[0]);
				// System.out.println(s2[0]);
				// System.out.println(lat + "," + lon);
			}

			historyInterferenceInfo.add(historySourceList);
		}

		System.out.println("rsStationInfo" + rsStationInfo);
		System.out.println("bsStationInfo" + bsStationInfo);
		System.out.println("frontIdInfo" + frontIdInfo);
		System.out.println("unsettledFrontIdInfo" + unsettledFrontIdInfo);

		JSONObject result=new JSONObject();
		result.put("rsStation", rsStationInfo);
		result.put("frontId", frontIdInfo);
		result.put("bsStation", bsStationInfo);
		result.put("unsettledFrontId", unsettledFrontIdInfo);
		result.put("historyInterference", historyInterferenceInfo);
		ResponseUtil.write(response, result);
		return null;
	}
	
	/*
	 * 建模函数
	 */
	/*
     * 离线获取前置机经纬度以及对应基站的经纬度
     */
    /**
	 * 
	 * @param
	 * @param
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getSelectTime")
	public String getSelectTime(@RequestParam(value="frontId",required=false)String frontId,HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		JSONObject jsonObject=new JSONObject();
		String[] fId=null;
		if(frontId!=null&&!frontId.equals("")){
		    fId=frontId.split(",");
		}
		String[] FrontIds=new String[fId.length];
		int len=0; //建模前置机的个数
		
		for(int i=0;i<fId.length;i++) {
			if(!fId[i].equals("")) {
				map.put("frontId", fId[i]);
				map.put("table_name","bs_info");
				String front_Id=interferencequeryService.get_frontId(map);
				FrontIds[len]=front_Id; //长整型
				len++;
			}
		}
		long[] Mintime=new long[len]; //记录不同前置机的最大最小时间
		long[] Maxtime=new long[len];
		for(int j=0;j<len;j++) {
			map.put("frontId", FrontIds[j]);
			map.put("table_name","fs_signal_overall");
			int largedate=interferencequeryService.get_largedate(map);
			int earlydate=interferencequeryService.get_earlydate(map);
			map.put("table_name","frequencySpectrum_" + FrontIds[j]+"_"+largedate);
			long largetime=interferencequeryService.get_latestFSTime(map);
			map.put("table_name","frequencySpectrum_" + FrontIds[j]+"_"+earlydate);
			long earlytime=interferencequeryService.get_earlyFSTime(map);
			Mintime[j]=earlytime;
			Maxtime[j]=largetime;
		}
		long min_time=getMax(Mintime);
		long max_time=getMin(Maxtime);
		String endTime=converttimesecond(String.valueOf(max_time));
		String startTime=converttimesecond(String.valueOf(min_time));//提前1个小时
		jsonObject.put("startTime",startTime);
		jsonObject.put("endTime",endTime);
		ResponseUtil.write(response, jsonObject);
		return null;
	}
	
	
    public static long getMax(long[] arr) {    
         long max = arr[0];
         for (int x = 1; x < arr.length; x++) { 
                 if (arr[x] > max)  
                        max = arr[x];  
         }  
         return max;   
    }  
    public static long getMin(long[] arr) {    
         long min = arr[0];
         for (int x = 1; x < arr.length; x++) { 
                 if (arr[x] < min)  
                        min = arr[x];  
         }  
         return min;   
    }
	
    /**
	 *  建模函数
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/createModel")
	public String createModel(@RequestParam(value="frontId",required=false)String frontId,@RequestParam(value="modelType",required=false)String modelType,
			@RequestParam(value="modelBeginTime",required=false)String modelBeginTime,@RequestParam(value="modelEndTime",required=false)String modelEndTime,HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		JSONObject jsonObject=new JSONObject();
		int resultTotal=0;
		String[] fId=null;
		if(frontId!=null&&!frontId.equals("")){
		    fId=frontId.split(",");
		}
		String FrontIds="";
		// int len=0; //建模前置机的个数
		for(int i=0;i<fId.length;i++) {
			if(!fId[i].equals("")) {
				map.put("frontId", fId[i]);
				map.put("table_name","bs_info");
				String front_Id=interferencequeryService.get_frontId(map);
				if(i<fId.length-1) {
					FrontIds=FrontIds+front_Id+",";
				}
				else {
					FrontIds=FrontIds+front_Id;
				}
			}
		}
		map.put("table_name", "inf_config");
		map.put("frontId", FrontIds);
		map.put("modelType", modelType);
		map.put("modelBeginTime", modelBeginTime);
		map.put("modelEndTime", modelEndTime);
		map.put("modelStatus", 1);
		resultTotal=interferencequeryService.createModel(map);
		if(resultTotal>0){
			jsonObject.put("success", true);
		}else{
			jsonObject.put("success", false);
		}
		ResponseUtil.write(response, jsonObject);
		return null;
	}
	
	/**
	 *  建模函数
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/cancelModel")
	public String cancelModel(HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		JSONObject jsonObject=new JSONObject();
		int resultTotal=0;
		map.put("table_name", "inf_config");
		map.put("modelStatus", 2);
		resultTotal=interferencequeryService.cancelModel(map);
		if(resultTotal>0){
			jsonObject.put("success", true);
		}else{
			jsonObject.put("success", false);
		}
		ResponseUtil.write(response, jsonObject);
		return null;
	}
	
	/**
	 * 
	 *获取建模状态
	 */
	@RequestMapping("/modelStatus")
	public String getmodelStatus(HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		List<InfConfig> configList = new ArrayList<InfConfig>();
		map.put("table_name","inf_config");
		List<InfConfig> sub_configList = interferencequeryService.get_Status(map);
		configList.addAll(sub_configList);
		JSONArray jsonArray1=JSONArray.fromObject(configList); 
        JSONObject json=new JSONObject();  
        json=jsonArray1.getJSONObject(0);  
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("ModelStatus", json.get("modelStatus"));
		ResponseUtil.write(response, jsonObject);
		return null;
	}
	
	/**
	 * 干扰查询导出当前页的数据
	 * 
	 * @param data
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/exportcurrentpageQuery")
	public String exportcurrentpage(@RequestParam(value = "data") String data, HttpServletResponse response) throws Exception {
		Workbook wb = new HSSFWorkbook();

		String headers[] = {"告警级别","前置机号", "基站", "开始时间", "结束时间", "上下行", "机车号", "公里标", "干扰强度", 
				"干扰带宽", "被干扰概率", "干扰频道", "最强干扰频道", "次强干扰频道", "干扰类型", "干扰源类型", "是否已处理","告警解除方式","告警解除时间" };
		List<Interference> interference_all = new ArrayList<Interference>();
		if (data != null && !data.equals("null") && !data.equals("") && data.trim().length() > 1) {
			JSONArray jsonArray = JSONArray.fromObject(data);
			for (int i = 0; i < jsonArray.size(); i++) {
				Interference interference = new Interference();
				interference.setAlarmLevel(jsonArray.getJSONObject(i).getString("alarmLevel"));;
				interference.setFrontId(jsonArray.getJSONObject(i).getString("frontId"));
				interference.setBSName(jsonArray.getJSONObject(i).getString("BSName"));
				interference.setTimeBegin(jsonArray.getJSONObject(i).getString("timeBegin"));
				interference.setTimeEnd(jsonArray.getJSONObject(i).getString("timeEnd"));
				interference.setDirection(jsonArray.getJSONObject(i).getString("direction"));
				interference.setEngineID(jsonArray.getJSONObject(i).getString("engineID"));
				interference.setKilometer(jsonArray.getJSONObject(i).getString("kilometer"));
				interference.setInfIntensity(jsonArray.getJSONObject(i).getString("infIntensity"));
				interference.setInfBandWidth(jsonArray.getJSONObject(i).getString("infBandWidth"));
				interference.setInfProbability(jsonArray.getJSONObject(i).getString("infProbability"));
				interference.setInfChannel(jsonArray.getJSONObject(i).getString("infChannel"));
				interference.setInfMaxChannel(jsonArray.getJSONObject(i).getString("infMaxChannel"));
				interference.setInfSecChannel(jsonArray.getJSONObject(i).getString("infSecChannel"));
				interference.setInfType(jsonArray.getJSONObject(i).getString("infType"));
				interference.setInfSourceType(jsonArray.getJSONObject(i).getString("infSourceType"));
				interference.setDisposed(jsonArray.getJSONObject(i).getString("disposed"));
				interference.setReleaseWay(jsonArray.getJSONObject(i).getString("releaseWay"));
				interference.setReleaseTime(jsonArray.getJSONObject(i).getString("releaseTime"));
				interference_all.add(interference);
			}
		}
		try {
			ExcelUtil.fillExcelData_InterferenceQuery(interference_all, wb, headers);
			ResponseUtil.export(response, wb, "告警干扰记录" + FormatDate.formatDate() + ".xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 导出所有干扰记录
	 * 
	 * @param
	 * @param
	 * @param
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/exportQuery")
	public String exportQuery(@RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime, 
			@RequestParam(value = "frontId", required = false) String frontId, @RequestParam(value = "interference_type", required = false) String interference_type, 
			@RequestParam(value="disposed",required=false)String disposed,@RequestParam(value="releaseWay",required=false)String releaseWay,@RequestParam(value="isHistory",required=false)String isHistory,HttpServletResponse response) throws Exception {
		Workbook wb = new HSSFWorkbook();
		String headers[] = {"告警级别", "前置机号", "基站", "开始时间", "结束时间", "上下行", "机车号", "公里标", "干扰强度", "干扰带宽", "干扰概率", "干扰频道", "最强干扰频道", "次强干扰频道", "干扰类型","干扰源类型", "是否已处理","告警解除方式","告警解除时间" };
		Map<String, Object> map = new HashMap<String, Object>();
//		if (frontId != null && !frontId.equals("")) {
//			map.put("frontId", frontId);
//			map.put("table_name", "bs_info");
//			String front_Id = interferencequeryService.get_frontId(map);
//			map.put("frontId", front_Id);
//		}
		if (frontId != null && frontId.trim().length() > 0) {
			
			String[] subdistrict = frontId.split(",");
			String[] frontID = new String[subdistrict.length];
			
			for (int i = 0; i < subdistrict.length; i++) {
				if (subdistrict[i].trim().length() < 1) continue;
				map.put("frontId", subdistrict[i]);
				map.put("table_name","bs_info");
				frontID[i] = interferencequeryService.get_frontId(map);
			}
			List<String> subList = Arrays.asList(frontID);
			map.put("district", subList);
			System.out.println(map);
		}
		if (interference_type != null && interference_type.trim().length() > 0) {
			String[] infTypes = interference_type.split(",");			
			map.put("interference_types", Arrays.asList(infTypes));
		}
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", startTime);
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", endTime);
		}
		if(disposed!=null&&!disposed.equals("")){
			if(disposed.equals("是")) {
				map.put("disposed", "1");
			}
			else if(disposed.equals("否")) {
				map.put("disposed", "0");
			}		
		}
		if (releaseWay!=null && !releaseWay.equals("NaN")) {
			if (releaseWay.equals("自动消除")) {
				map.put("releaseWay", releaseWay);
			} else if (releaseWay.equals("手动确认")) {
				map.put("releaseWay", releaseWay);
			}
		}
		List<Interference> interferenceList = new ArrayList<Interference>();
		if(isHistory.equals("1")) {
			map.put("table_name","interference_history");
		}
		else {
			map.put("table_name","interference_real_time");
		}
		System.out.println(map);
		List<Interference> sub_sdcchList = interferencequeryService.find(map);
		interferenceList.addAll(sub_sdcchList);
		List<Interference> interferenceList_all = new ArrayList<Interference>();
		for (Interference interference : interferenceList) {
			    /*String Direction="下行";
	            String dis="否";
	            String kil="";
	            String fchannel="";
	            String schannel="";
				Object timestart = json.get("timeBegin");
				Object timeend = json.get("timeEnd");
				Object dir = json.get("direction");
				Object isdisposed=json.get("disposed");
				Object kilometer=json.get("kilometer");
				Object releasetime=json.get("releaseTime");
				Object firstchannel=json.get("infMaxChannel");
				Object secondchannel=json.get("infSecChannel");
				String start = converttime((String) timestart);
				String end = converttime((String) timeend);
				String rtime=converttime((String) releasetime);			
	            if (dir.equals("0"))
	            	Direction="上行";
	            if(isdisposed.equals("1"))
	            	dis="是";
	            kil=kilometer.toString();
	            if(kilometer.equals("0")) {
	            	kil="";
	            }
	            fchannel=firstchannel.toString();
	            if(firstchannel.equals("0"))
	            	fchannel="";
	            schannel=secondchannel.toString();
	            if(secondchannel.equals("0"))
	            	schannel="";
	            jsonArray.getJSONObject(i).put("timeBegin", start);
	            jsonArray.getJSONObject(i).put("timeEnd", end);
	            jsonArray.getJSONObject(i).put("direction", Direction);
	            jsonArray.getJSONObject(i).put("disposed", dis);
	            jsonArray.getJSONObject(i).put("kilometer", kil);
	            jsonArray.getJSONObject(i).put("releaseTime", rtime);
	            jsonArray.getJSONObject(i).put("infMaxChannel", fchannel);
	            jsonArray.getJSONObject(i).put("infSecChannel", schannel);*/
			String timestart;
			String timeend;
			String dir;
			String start;
			String end;
			String Direction = "下行";
			String dis="否";
            String kil="";
            String fchannel="";
            String schannel="";
			timestart = interference.getTimeBegin();
			timeend = interference.getTimeEnd();
			dir = interference.getDirection();
			String isdisposed=interference.getDisposed();
			String kilometer=interference.getKilometer();
			String releasetime=interference.getReleaseTime();
			String firstchannel=interference.getInfMaxChannel();
			String secondchannel=interference.getInfSecChannel();
			start = converttime(timestart);
			end = converttime(timeend);
			releasetime=converttime(releasetime);
			if (dir.equals("0"))
				Direction = "上行";
			if(isdisposed.equals("1"))
            	dis="是";
            kil=kilometer;
            if(kilometer.equals("0")) {
            	kil="";
            }
            fchannel=firstchannel;
            if(firstchannel.equals("0"))
            	fchannel="";
            schannel=secondchannel;
            if(secondchannel.equals("0"))
            	schannel="";
			interference.setTimeBegin(start);
			interference.setTimeEnd(end);
			interference.setDirection(Direction);
			interference.setDisposed(dis);
			interference.setKilometer(kil);
			interference.setInfMaxChannel(fchannel);
			interference.setInfSecChannel(schannel);
			interference.setReleaseTime(releasetime);
			interferenceList_all.add(interference);
		}
		try {
			ExcelUtil.fillExcelData_InterferenceQuery(interferenceList_all, wb, headers);
			ResponseUtil.export(response, wb, "告警干扰记录" + FormatDate.formatDate() + ".xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 干扰查询导出当前页的数据
	 * 
	 * @param data
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/exportcurrentpageAlarm")
	public String exportcurrentpageAlarm(@RequestParam(value = "data") String data, HttpServletResponse response) throws Exception {
		Workbook wb = new HSSFWorkbook();

		String headers[] = { "告警级别", "前置机号", "基站", "开始时间", "结束时间", "上下行", "干扰强度", "干扰频道", "干扰类型", "干扰源类型", "是否处理" };
		List<AlarmHistoryExport> interference_all = new ArrayList<AlarmHistoryExport>();
		if (data != null && !data.equals("null") && !data.equals("")) {
			JSONArray jsonArray = JSONArray.fromObject(data);
			for (int i = 0; i < jsonArray.size(); i++) {
				AlarmHistoryExport interference = new AlarmHistoryExport();
				interference.setFrontId(jsonArray.getJSONObject(i).getString("frontId"));
				interference.setBSName(jsonArray.getJSONObject(i).getString("BSName"));
				interference.setTimeBegin(jsonArray.getJSONObject(i).getString("timeBegin"));
				interference.setTimeStamp(jsonArray.getJSONObject(i).getString("timeStamp"));
				interference.setDirection(jsonArray.getJSONObject(i).getString("direction"));
				interference.setInfIntensity(jsonArray.getJSONObject(i).getString("infIntensity"));
				interference.setInfChannel(jsonArray.getJSONObject(i).getString("infChannel"));
				interference.setInfType(jsonArray.getJSONObject(i).getString("infType"));
				interference.setInfSourceType(jsonArray.getJSONObject(i).getString("infSourceType"));
				interference.setAlarmLevel(jsonArray.getJSONObject(i).getString("alarmLevel"));
				interference.setIsDisposed(jsonArray.getJSONObject(i).getString("isDisposed"));
				interference_all.add(interference);
			}
		}
		try {
			ExcelUtil.fillExcelData_InterferenceAlarm(interference_all, wb, headers);
			ResponseUtil.export(response, wb, "导出excel" + FormatDate.formatDate() + ".xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 导出所有干扰记录
	 */
	@RequestMapping("/exportAlarm")
	public String exportAlarm(@RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime, 
			@RequestParam(value = "frontId", required = false) String frontId, HttpServletResponse response) throws Exception {
		Workbook wb = new HSSFWorkbook();
		String headers[] = { "告警级别", "前置机号", "基站", "开始时间", "结束时间", "上下行", "干扰强度", "干扰频道", "干扰类型", "干扰源类型", "是否处理" };
		Map<String, Object> map = new HashMap<String, Object>();
		if (frontId != null && !frontId.equals("")) {
			map.put("frontId", frontId);
			map.put("table_name", "bs_info");
			String front_Id = interferencequeryService.get_frontId(map);
			map.put("frontId", front_Id);
		}
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", startTime);
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", endTime);
		}
		List<AlarmHistory> alarmhistoryList = new ArrayList<AlarmHistory>();
		map.put("table_name", "history_alarm");
		List<AlarmHistory> sub_sdcchList = interferencequeryService.findalarmhistory(map);
		alarmhistoryList.addAll(sub_sdcchList);
		//JSONObject result = new JSONObject();
		JSONArray jsonArray1 = JSONArray.fromObject(alarmhistoryList);
		List<AlarmHistoryExport> alarmhistoryList_all = new ArrayList<AlarmHistoryExport>();
		for (int i = 0; i < jsonArray1.size(); i++) {
			AlarmHistoryExport interference = new AlarmHistoryExport();
			;
			JSONObject json = new JSONObject();
			json = jsonArray1.getJSONObject(i);
			try {
				map.put("table_name", "interference_new");
				map.put("frontId", (String) json.get("frontId"));
				map.put("endTime", (String) json.get("timeStamp"));
				map.put("direction", (String) json.get("direction"));
				List<Interference> inteferencelist = interferencequeryService.findresult(map);
				JSONArray tmp = JSONArray.fromObject(inteferencelist);
				jsonArray1.getJSONObject(i).putAll(tmp.getJSONObject(0));
				Object timestamp;
				Object timestart;
				Object disposed;
				Object dir;
				String time;
				String timebegin;
				String str = "否";
				String Direction = "下行";
				timestart = json.get("timeBegin");
				timestamp = json.get("timeStamp");
				disposed = json.get("isDisposed");
				timebegin = converttime((String) timestart);
				time = converttime((String) timestamp);
				dir = json.get("direction");
				if (disposed.equals("1")) {
					str = "是";
				}
				if (dir.equals("0")) {
					Direction = "上行";
				}
				interference.setFrontId((String) json.get("frontId"));
				interference.setBSName((String) json.get("BSName"));
				interference.setTimeBegin(timebegin);
				interference.setTimeStamp(time);
				interference.setDirection(Direction);
				interference.setInfIntensity((String) json.get("infIntensity"));
				interference.setInfChannel((String) json.get("infChannel"));
				interference.setInfType((String) json.get("infType"));
				interference.setInfSourceType((String) json.get("infSourceType"));
				interference.setAlarmLevel((String) json.get("alarmLevel"));
				interference.setIsDisposed(str);
			} catch (Exception e) {
				Object timestamp;
				Object disposed;
				Object dir;
				String time;
				//String timebegin;
				String str = "否";
				String Direction = "下行";
				timestamp = json.get("timeStamp");
				disposed = json.get("isDisposed");
				time = converttime((String) timestamp);
				dir = json.get("direction");
				if (disposed.equals("1")) {
					str = "是";
				}
				if (dir.equals("0")) {
					Direction = "上行";
				}
				interference.setFrontId((String) json.get("frontId"));
				interference.setBSName((String) json.get("BSName"));
				interference.setTimeBegin("");
				interference.setTimeStamp(time);
				interference.setDirection(Direction);
				interference.setInfIntensity((String) json.get("infIntensity"));
				interference.setInfChannel((String) json.get("infChannel"));
				interference.setInfType((String) json.get("infType"));
				interference.setInfSourceType((String) json.get("infSourceType"));
				interference.setAlarmLevel((String) json.get("alarmLevel"));
				interference.setIsDisposed(str);
			}
			alarmhistoryList_all.add(interference);

		}
		try {
			ExcelUtil.fillExcelData_InterferenceAlarm(alarmhistoryList_all, wb, headers);
			ResponseUtil.export(response, wb, "导出excel" + FormatDate.formatDate() + ".xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping("/findBsInfo")
	public void findBsInfo() {
	}
	
	
   
	//查看历史干扰源
	@RequestMapping("/infhistorysource")
	public String check(@RequestParam(value="page",required=false)String page,@RequestParam(value="rows",required=false)String rows,
			@RequestParam(value = "frontId", required = false) String frontId,HttpServletResponse response) throws Exception {
		PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		Map<String,Object> map=new HashMap<String,Object>();
		if (frontId != null && !frontId.equals("")) {
			map.put("frontId", frontId);
		}
		map.put("size", pageBean.getPageSize());
		List<InfHistorySource> interferenceList = new ArrayList<>();
		map.put("table_name","history_inf_source");
		List<InfHistorySource> subList = interferencequeryService.findinfhistorysource(map);
		interferenceList.addAll(subList);
		int total=interferencequeryService.getTotalinfhistorysource(map);
		JSONObject result=new JSONObject();
		JSONArray jsonArray=JSONArray.fromObject(interferenceList);
//		for (int i = 0; i < jsonArray.size(); i++) {
//            JSONObject json=new JSONObject();  
//            json=jsonArray.getJSONObject(i);  
//            Object createTime;
//            String time;
//            createTime=json.get("createTime");
//            time=converttime((String)createTime);
//            jsonArray.getJSONObject(i).put("createTime", time);
//            
//        }  
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
		return null;
	}
	
	//保存历史干扰源记录
	@RequestMapping("/saveData")
	public String save(InfHistorySource historySource, HttpServletResponse response, Integer flag) throws Exception {
		
		int resultTotal = 0; // 操作的记录条数
		JSONObject result = new JSONObject();
		
		if (flag == 1) { // 新增
			
			historySource.setCreateTime(Long.toString(System.currentTimeMillis()));
			try {
				resultTotal=interferencequeryService.insertHistorySource(historySource);
			}catch(Exception e) {
				e.printStackTrace();
			}
			
		} else {
			Map<String, Object>map = BeanUtils.describe(historySource);
			//System.out.println(map);
			resultTotal = interferencequeryService.updateInfHistorySource(map);
		}

		if (resultTotal > 0) {
			result.put("success", true);
		} else {
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 上传
	 */
	@RequestMapping("/upload")
	public void upload(HttpServletRequest request, HttpServletResponse response, Integer uploadFlag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("table_name", "history_inf_source");
		map.put("CreateTime", "0 OR 1=1");
		if (uploadFlag == 2) {
			interferencequeryService.delete(map);
		}
		
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();

			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					//String path = file.getOriginalFilename();
					String path = "已导入" + new Date().getTime() + file.getOriginalFilename();
					// 上传
					File newFile = new File(path);
			
					file.transferTo(newFile);
					// 写数据进数据库
					POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(newFile));
					newFile.delete();
					HSSFWorkbook wb = new HSSFWorkbook(fs);
					HSSFSheet hssfSheet = wb.getSheetAt(0); // 获取第一个Sheet页
					JSONObject result = new JSONObject();
					try {
						if (hssfSheet != null) {
							for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
								HSSFRow hssfRow = hssfSheet.getRow(rowNum);
								if (hssfRow == null) {
									continue;
								}
								String  id = ExcelUtil.formatCell(hssfRow.getCell(15));
								if (StringUtil.isEmpty(id) || existId(id, null)) {
									System.out.println("id: " + id + "为空或者已存在，跳过该行");
									continue;
								}
								InfHistorySource historySource = new InfHistorySource(ExcelUtil.formatCell(hssfRow.getCell(0)), 
										ExcelUtil.formatCell(hssfRow.getCell(1)), ExcelUtil.formatCell(hssfRow.getCell(2)), 
										ExcelUtil.formatCell(hssfRow.getCell(3)), ExcelUtil.formatCell(hssfRow.getCell(4)), 
										ExcelUtil.formatCell(hssfRow.getCell(5)), ExcelUtil.formatCell(hssfRow.getCell(6)), 
										ExcelUtil.formatCell(hssfRow.getCell(7)), ExcelUtil.formatCell(hssfRow.getCell(8)), 
										ExcelUtil.formatCell(hssfRow.getCell(9)), ExcelUtil.formatCell(hssfRow.getCell(10)), 
										ExcelUtil.formatCell(hssfRow.getCell(11)), ExcelUtil.formatCell(hssfRow.getCell(12)), 
										ExcelUtil.formatCell(hssfRow.getCell(13)), ExcelUtil.formatCell(hssfRow.getCell(14)), ExcelUtil.formatCell(hssfRow.getCell(15)),
										Double.valueOf(ExcelUtil.formatCell(hssfRow.getCell(16))).intValue(), Double.valueOf(ExcelUtil.formatCell(hssfRow.getCell(17))).intValue(), 
										Double.valueOf(ExcelUtil.formatCell(hssfRow.getCell(18))).intValue(), Double.valueOf(ExcelUtil.formatCell(hssfRow.getCell(19))).intValue(), 
										Double.valueOf(ExcelUtil.formatCell(hssfRow.getCell(20))).intValue(), ExcelUtil.formatCell(hssfRow.getCell(21)));
								
								interferencequeryService.insertHistorySource(historySource);
							}
						}
						result.put("success", true);
					} catch (Exception e) {
						result.put("success", false);
						e.printStackTrace();
					}
					ResponseUtil.write(response, result);
					wb.close();
				}
			}
		}
	}
	
	
	
	/**
	 * 判断是否存在指定用户名
	 */
	@RequestMapping("/existId")
	public Boolean existId(String CreateTime, HttpServletResponse response) throws Exception {
		if (StringUtil.isEmpty(CreateTime)) {
			return true;
		}
		Map<String, Object> map = new HashMap<>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("table_name", "history_inf_source");
		map.put("CreateTime", CreateTime);
		
		boolean hasDuplicate = false;
		JSONObject result = new JSONObject();
		List<InfHistorySource> list = interferencequeryService.findinfhistorysource(map);
		if (list == null || list.size() < 1) {
			result.put("exist", false);
		} else {
			result.put("exist", true);
			hasDuplicate = true;
		}
		if (response != null) {
			ResponseUtil.write(response, result);
			return null;
		}
		return hasDuplicate;
	}
	
	String headers[] = {"扫描时间", "前置机号", "基站", "文件名编号", "MCC", "MNC", "LAC", "CID", "BCCH", "BSIC", "RXLEV", "TRXs"};
	/**
	 * 导出历史Fscan
	 */
	@RequestMapping("/exporthistoryfscan")
	public void export(@RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime,
			HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Workbook wb = new HSSFWorkbook();
		// 当天00:00的时间戳
		Long earlyMorningTime = System.currentTimeMillis() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
		// 当前时间戳
		Long nowTime = System.currentTimeMillis();
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", DateUtil.longToString(Long.parseLong(startTime), "yyyyMMdd"));
		} else {
			map.put("startTime", DateUtil.longToString(earlyMorningTime, "yyyyMMdd"));
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", DateUtil.longToString(Long.parseLong(endTime), "yyyyMMdd"));
		} else {
			map.put("endTime", DateUtil.longToString(nowTime, "yyyyMMdd"));
		}
		List<String> table_names = interferencequeryService.findFscanTableNames(map);
		
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", startTime);
		} else {
			map.put("startTime", null);
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", endTime);
		} else {
			map.put("endTime", null);
		}
		
		List<FScan> fscanList = new ArrayList<FScan>();
		fscanList.clear();
		List<FScan> sub_fscanList = null;
		if (table_names != null) {
			for (int i = 0; i < table_names.size(); i++) {
				sub_fscanList = null;
				map.put("table_name", table_names.get(i));
				sub_fscanList = interferencequeryService.getFScan(map);
				if (sub_fscanList != null) {
					fscanList.addAll(sub_fscanList);
				}
			}
		}
		InterferenceQueryController.ListSort(fscanList);
		ExcelUtil.fillExcelHistoryData_FScan(fscanList, wb, headers);
		ResponseUtil.export(response, wb, "Fscan" + FormatDate.formatDate() + ".xls");
	}
	
	/**
	 * 对List中每个对象元素升序排序 
	 */
	private static void ListSort(List<FScan> list) {
		if (list == null || list.size() < 2)
			return;
		Collections.sort(list, new Comparator<FScan>() {
			@Override
			public int compare(FScan fs1, FScan fs2) {
				try {
					Long l1 = Long.parseLong(fs1.getScanTime());
					Long l2 = Long.parseLong(fs2.getScanTime());
					if (l1 < l2) {
						return -1;
					} else if (l1 > l2) {
						return 1;
					} else {
						return 0;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
	}
}